Check if Mouse LButton is down?

14,205

There is a Windows API function GetAsyncKeyState(), which despite its name is also usable to get the state of the mouse buttons. The linked documentation directly contains the answer to your question:

The GetAsyncKeyState function works with mouse buttons. However, it checks on the state of the physical mouse buttons, not on the logical mouse buttons that the physical buttons are mapped to. For example, the call GetAsyncKeyState(VK_LBUTTON) always returns the state of the left physical mouse button, regardless of whether it is mapped to the left or right logical mouse button. You can determine the system's current mapping of physical mouse buttons to logical mouse buttons by calling GetSystemMetrics(SM_SWAPBUTTON) which returns TRUE if the mouse buttons have been swapped.

The result type is short, to check for the most significant bit just test whether the value is negative.

Share:
14,205
P. Duw
Author by

P. Duw

Updated on June 17, 2022

Comments

  • P. Duw
    P. Duw almost 2 years

    How do I check if the Left button of my mouse is currently pressed down/dragging something(I preffer the first possibility).

    I tried Mouse.IsDraging,but no result.

    NOTE: I handle mouse messages in my application so its no problem if its a WM,just share a way to accomplish my task.

  • Vassilis
    Vassilis over 8 years
    VERY nice. Although you give the solution about checking the most significant bit, could you describe the formal way of getting it?
  • mghie
    mghie over 8 years
    @VassilisGr: Sorry, I don't really understand this request. Leaving type coercion to the compiler is probably the best (i.e. the formal?) thing to do, as it isolates you from issues like 32 vs. 64 bit compilation. Or do you mean how to test whether that single bit in the result is set or not? Just use something like (result and $8000) <> 0.
  • Vassilis
    Vassilis over 8 years
    was looking for (result and $8000) <> 0. Thanks!