Detect if mouse button is down

给你一囗甜甜゛ 提交于 2020-02-15 09:47:41

问题


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

回答1:


Use this to determine if the button is pressed.

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

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




回答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.




回答3:


In first - need DEFINE BUTTON ID(or another object ID) in begin code:

#define ID_BUTTON1      105

Then AFTER creationale of hWnd - we make button:

   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.

And then add trigger in function:

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
}


来源:https://stackoverflow.com/questions/18318911/detect-if-mouse-button-is-down

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!