Detect if mouse button is down
Solution 1
Use this to determine if the button is pressed.
if((GetKeyState(VK_LBUTTON) & 0x8000) != 0)
http://vcpptips.wordpress.com/tag/vk_lbutton/
Solution 2
The application can catch messages and process being sent to your window indicating a state change of any mouse button.
When the left button is pressed a
WM_LBUTTONDOWN
is sent.
When it is released
WM_LBUTTONUP
is sent.
Please read here for various messages being sent to indicate mouse events.
Solution 3
Use the below to detect left mouse button press
if(GetAsyncKeyState(VK_LBUTTON)){
//your code controls here
}
You can find more controls here : https://docs.microsoft.com/en-us/windows/win32/api/winuser/nf-winuser-getasynckeystate
Also if the GetAsyncKeyState(VK_LBUTTON)
shows a syntax error, try including winuser.h by adding #include <winuser.h>
in the includes of your code.
Here is an example
if(GetKeyState(VK_LBUTTON))
{ //finding clicked position
HWND hWnd = FindWindowA(0,("Motion Paths"));
::GetWindowThreadProcessId(hWnd,&pid);
if (hWnd) { cout << "Found" << endl;}
POINT p;
GetCursorPos(&p);
if (ScreenToClient(hWnd, &p))
{
int mouseX = p.x;
int mouseY = p.y;
cout<< p.x << " "<< p.y <<endl;
}
}
Jordan B
Updated on July 09, 2022Comments
-
Jordan B almost 2 years
I am new to c++ and I am trying to activate a line of code only when the left mouse button is held down. In this example, my code works but it seems that it just toggles it. When I click, it spams the H key then, when I click again, it stops.
Currently I have this code:
if ((GetKeyState(VK_LBUTTON))) { keybd_event(VkKeyScan('H'),0,0,0); Sleep ( 30 ); }
Edit:
I have inside the function:
int WINAPI WinMain ( HINSTANCE hInst, HINSTANCE P, LPSTR CMD, int nShowCmd );
-
Jordan B over 10 yearsThanks. At first it didn't work, but after reading the comments I tried replacing the 0x80 with 0x100 and works now. From what I read its 100 because I am using 64bit.
-
Jonathan Potter over 10 yearsA less fiddly way is
if (GetKeyState(VK_LBUTTON) < 0) { }
, fwiw. -
Remy Lebeau about 4 years
0x100
is the wrong value to mask with. It needs to be0x8000
instead.< 0
is better, though -
KeyC0de over 3 years@RemyLebeau The
&
method is more fiddly but is faster.