Getting mouse cursor position and button state on Windows

17,037

Solution 1

If you want to poll/query the current cursor position, you can use GetCursorPos. To see the button states, use GetAsyncKeyState.

If you are implementing a message loop in a window, the notification you will get for a mouse movement is WM_MOUSEMOVE. You will be notified of mouse inputs through the notifications listed here.

Solution 2

WM_LBUTTONUP is as good as any window message, for windowed games is great because it is generated only when the mouse clicks the client area, so you can resize and move the window freely.

As an alternative to direct input, you can use raw inputs which take up some more code to initialize, but it's the best way to go with the mouse movement since WM_INPUT is generated when the physical mouse moves, not the cursor, so you can clip the cursor in the client area without worrying that the user may hit the side of the clip rect and the mouse movement messages won't be generated anymore. link

Share:
17,037
judeclarke
Author by

judeclarke

Updated on June 29, 2022

Comments

  • judeclarke
    judeclarke almost 2 years

    What is the most appropriate way of getting the mouse cursor position or button state on Windows (Windows 7 and above)? I previously used DirectInput, but I am not longer using it and do not wish to. I saw there is GetCursorPos, however, I do not see anything for getting mouse button states. I have read previously that just reading the window messages (such as WM_LBUTTONUP) was considered "slow" for real time applications, so I do not know of any other option.

  • Adrian McCarthy
    Adrian McCarthy almost 12 years
    If I recall correctly, GetCursorPos will be current as of the last message processed. If you want the key state to be consistent withthe position, you should use GetKeyState, which is also be current as of the last message processed.
  • jamesdlin
    jamesdlin almost 12 years
    @AdrianMcCarthy: No, GetCursorPos goes with GetAsyncKeyState, and GetMessagePos goes with GetKeyState.