16

If a mouse button is pressed and a window is shown that window will receive the MouseUp event when the mouse button is released.

Is it possible to detect, once the window is shown, whether or not a mouse button is already pressed?

RobS
  • 3,807
  • 27
  • 34
  • you may want to look at GetAsyncKeyState(VK_LBUTTON) –  Feb 23 '12 at 12:44
  • 5
    Note that `GetAsyncKeyState` returns the physical mouse button state, whilst `GetKeyState` returns logical (regarding what have you set in the `Switch primary and secondary buttons` option in mouse settings). – TLama Feb 23 '12 at 12:57

2 Answers2

17

I would try this:

procedure TForm1.FormShow(Sender: TObject);
begin
  if GetKeyState(VK_LBUTTON) and $8000 <> 0 then
    ShowMessage('Left mouse button is pressed...')
  else
    ShowMessage('Left mouse button is not pressed...')
end;
TLama
  • 75,147
  • 17
  • 214
  • 392
  • 3
    Thanks, this is correct.... almost. The result of GetKeyState needs to be compared with $8000 (see http://stackoverflow.com/a/3422706/41338 ) to check whether the correct bits are set. – RobS Feb 23 '12 at 13:13
  • You're definitely right. Thanks! I'll update the post. Sorry for misleading. – TLama Feb 23 '12 at 13:18
9

To answer your question directly, you can test for mouse button state with GetKeyState or GetAsyncKeyState. The virtual key code you need is VK_LBUTTON.

The difference between these is that GetKeyState reports the state at the time that the currently active queued message was posted to your queue. On the other hand, GetAsynchKeyState gives you the state at the instant that you call GetAsynchKeyState.

From the documentation of GetKeyState:

The key status returned from this function changes as a thread reads key messages from its message queue. The status does not reflect the interrupt-level state associated with the hardware. Use the GetAsyncKeyState function to retrieve that information. An application calls GetKeyState in response to a keyboard-input message. This function retrieves the state of the key when the input message was generated.

I suspect that you should be using GetKeyState but I can't be 100% sure because I don't actually know what you are trying to achieve with this information.

David Heffernan
  • 601,492
  • 42
  • 1,072
  • 1,490
  • Thanks for the useful explanation of the difference between the two functions. You're correct in that GetKeyState is what I need. The dull extra information as to why I need this is that I'm creating a form whose output is based up on the last mouse button released. Originally I was counting the mouse buttons as they were pressed and counting them out as released but sometimes one of the mouse buttons might be pressed before the form was shown. However, this command means I can now check on each mouseup event whether any of the other mouse buttons are still pressed. – RobS Feb 23 '12 at 13:18