Tracking click of the mouse over a button

siva_r10 used Ask the Experts™
I have a dialog with a button on it. I would like to perform some operation when the user clicks and holds the button. How can I do this? The Mouse move events are available for the dialog, but not for the button. How should I handle this?

Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®

you need to subclass the button, to do this:
1. Go to ClassView tab in the explorer
2. Right click the top node (where it says ... classes)
3. Select New Class
4. Enter the name of the new class
5. In Base class combo, select CButton
6. Press OK
A .cpp and .h files are added for the new class.

1. open the .cpp file
2. Open class wizard (Ctrl-W)
3. Add a message handler for WM_LBUTTONDOWN message and write the necessary code

one last thing:
1. go to the dialog class header file that contains the button
2. open the class wizard and add a member variable for the button of type CButton
3. open the header file of the dialog class and change the data member definition from CButton to CMyButton where CMyButton is the new button class. Add he necessary header file at top that defines the new button class

now you can override the button message as you like. remeber to call the base class message handler for default processing.



Hi Nabehs,

Thanks. This partly works. But, I need to perform the activity as long as the user holds the button pressed. How can I keep track of when the user releases the mouse?


at WM_LBUTTONDOWN start a timer with the period you want. Create a data member of type bool : bool m_bPressed. Set at WM_LBUTTONDOWN to true and at WM_LBUTTONUP to false. Once the timer gets fired, that means the user has been pressing the button for sometime (the time you want), and the timer handler should check if the m_bPressed it true, then you know that the user kept the button pressed.
Freelance programmer / Consultant
In your dlg override the PreTranslateMessage should you have not done so already.
Trap the WM_LBUTTONDOWN message.
Check the hwnd and see if it your button (msg.hwnd == yourBtn.GetSafeHwnd())
IF it is then use SetCapture() so your dlg receives the mouse messages.

Also trap the LBUTTONUP message and test that you have the mouse captured (GetCapture() == this)
Release the mouse if you had it captured and finish your processing.

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial