检测鼠标按钮是否已关闭

时间:2013-08-19 16:43:31

标签: c++ windows winapi mouseevent

我是c ++的新手,当按住鼠标左键时,我正在尝试激活一行代码 。在这个例子中,我的代码可以正常工作,但它似乎只是切换它。当我点击时,它会阻止 H 键,然后当我再次点击时,它会停止。

目前我有这段代码:

if ((GetKeyState(VK_LBUTTON)))
{
    keybd_event(VkKeyScan('H'),0,0,0);
    Sleep ( 30 );
}

修改:

我在函数内部:

int WINAPI WinMain ( HINSTANCE hInst, HINSTANCE P, LPSTR CMD, int nShowCmd );

4 个答案:

答案 0 :(得分:10)

使用此选项确定是否按下按钮。

if((GetKeyState(VK_LBUTTON) & 0x100) != 0)

http://vcpptips.wordpress.com/tag/vk_lbutton/

答案 1 :(得分:1)

应用程序可以捕获发送到窗口的消息和进程,指示任何鼠标按钮的状态更改。

按下左按钮时

WM_LBUTTONDOWN
发送

发布时

WM_LBUTTONUP
发送

read here for various messages being sent to indicate mouse events

答案 2 :(得分:1)

使用以下内容检测鼠标左键按下

if(GetAsyncKeyState(VK_LBUTTON)){
   //your code controls here
 }

您可以在此处找到更多控件:https://docs.microsoft.com/en-us/windows/win32/api/winuser/nf-winuser-getasynckeystate

如果GetAsyncKeyState(VK_LBUTTON)显示语法错误,请尝试通过在代码的包含位置添加#include <winuser.h>来包含winuser.h。

这是一个例子

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;
            }
    }

答案 3 :(得分:-2)

首先 - 在开始代码中需要DEFINE BUTTON ID(或其他对象ID):

#define ID_BUTTON1      105

然后在创建hWnd之后 - 我们制作按钮:

   HWND HwndButton1 = CreateWindow( 
    L"BUTTON",  // Predefined class; Unicode assumed 
    L"OK",      // Button text 
    WS_TABSTOP | WS_VISIBLE | WS_CHILD | BS_DEFPUSHBUTTON,  // Styles 
    10,         // x position 
    10,         // y position 
    100,        // Button width
    100,        // Button height
    hWnd,     // Parent window
   (HMENU) ID_BUTTON1, // ID кнопки в меню
    NULL,            // Хуйня мне неведомая 8-)
    NULL);         // Pointer not needed.

然后在函数中添加触发器:

LRESULT CALLBACK WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam)
{
    int wmId=0, wmEvent;  //wmId NEED DEFINE null - if he is not available in event, else be ашипка
    PAINTSTRUCT ps;
    HDC hdc;

    switch (message)
    {
    case WM_COMMAND:
        wmEvent = HIWORD(wParam);  //  Name of EVENT - имя события
        wmId    = LOWORD(wParam);  // ID element for event - элемент с которым оно случилось

        case WM_LBUTTONDOWN: MessageBox(NULL, L"MouseL_Click", L"WndHeader", MB_OK | MB_ICONEXCLAMATION);  // Left Mouse Button pressed

        if( LOWORD(wParam) == 105 && WM_COMMAND == WM_LBUTTONDOWN){ // Клик по ID_BUTTON1 левым мышком
        EndDialog(hWnd,0);
        }
................  // Many another function
}