How to check the mouse button state

28 10 2009




A computer mouse is an input pointing device which having two buttons, known as Left & Right buttons. These buttons clicks primary source of events in the Windows Programming model. How can we check whether the mouse button is pressed or not from our application on a particular event.




Windows API provides GetKeyState function to retrieves the status of a specified virtual key. That means we have to use VK_LBUTTON or VK_RBUTTON, which are the virtual keys corresponding to the mouse L and R buttons. If the high order bit is 1, the key is down, otherwise key is up. Actually the return value of this function specifies the status of the given virtual key.




void CheckMouseButtonStatus()
   //Check the mouse left button is pressed or not
   if ((GetKeyState(VK_LBUTTON) & 0x80) != 0)
      AfxMessageBox(_T("LButton pressed"));
   //Check the mouse right button is pressed or not
   if ((GetKeyState(VK_RBUTTON) & 0x80) != 0)
      AfxMessageBox(_T("RButton pressed"));




Check the GetAsyncKeyState function too in the MSDN.




7 responses

10 03 2011


I was looking for a way to do this, outside of the standard way, which is to intercept mouse events.

12 03 2011
Sanoop S P

u r welcome 🙂
u can get more C++ and VC++ tips from my new blog

31 03 2011
John T

This is exactly what I needed, thanks!

One thing, I’m not sure if there’s something different about my setup, but I had to change 0x80 to 0x100:
if ((GetKeyState(VK_LBUTTON) & 0x100) != 0)

1 04 2011
Sanoop S P

Hello John,

Thanks a lot for your comment.

Actually the return value of GetKeyState function is a SHORT value and if the high-order bit is 1, the key is down; otherwise, it is up.
So we just need to do bitwise AND operation with 0x80 (binary equivalent is 10000000), so (GetKeyState(VK_LBUTTON) & 0×80) definitely would work. 😦

I am doubting in case if your OS is 64 bit we should have to use 0x100 (binary equivalent is 100000000). Please confirm.


26 11 2013
15 05 2014
web traffic rankings

Hi there just wanted to give you a brief heads up and let
you know a few of the pictures aren’t loading correctly.
I’m not sure why but I think its a linking issue.
I’ve tried it in two different web browsers and both show the
same results.

21 07 2014
Sanoop S P

I will check it.
Thank you very much for your suggestions.

With Best Regards,

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: