The system is behaving exactly as designed, but be aware that your code is going against all sound design principles. Specifically the use of Sleep
and ProcessMessages
in an input event handler are both to be frowned upon.
The reason that the program behaves this way is as follows:
- The user generates an input message by clicking the mouse.
- This input event is placed in the input queue for the appropriate thread.
- That thread is not servicing its input queue (it is sleeping) and so the input message, which is a mouse down, mouse up combo, sits there.
- The thread wakes up and enables the button.
- The button
OnClick
handler returns and the application's message loop continues. - In due course the mouse down and mouse up messages are processed (before the
CM_RELEASE
message) and so the buttonOnClick
handler runs again. - The button
OnClick
handler callsProcessMessages
which then handles theCM_RELEASE
and kills the form. - BOOM!
The whole concept of acknowledging the second click by the system when the respective button is disabled does not seem to be sound.
The key point is that the enabled state of the button is checked when the input message is processed and not when the input message is generated. It has to be this way because input messages are extremely low level things, and it's only the application that can interpret them as things like button clicks.
There are plenty of ways to fix your code, but I'm loathe to suggest any because this is clearly code for illustration. But I will say that all sound solutions will involve the removal of the calls to Sleep
and `ProcessMessages.