Detect if Mouse button already pressed before form shows
Asked Answered
S

2

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?

Straightforward answered 23/2, 2012 at 12:36 Comment(2)
you may want to look at GetAsyncKeyState(VK_LBUTTON)Caputto
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).Jacklight
J
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;
Jacklight answered 23/2, 2012 at 12:45 Comment(2)
Thanks, this is correct.... almost. The result of GetKeyState needs to be compared with $8000 (see https://mcmap.net/q/749349/-problem-with-onkeydown-in-delphi ) to check whether the correct bits are set.Straightforward
You're definitely right. Thanks! I'll update the post. Sorry for misleading.Jacklight
A
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.

Adlai answered 23/2, 2012 at 12:46 Comment(1)
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.Straightforward

© 2022 - 2024 — McMap. All rights reserved.