Search code examples
c++windowswinapimouseevent

Make a event for a mouse button even if application is minimized


I want to make an application that responds to a mouse button so I done this:

case WM_LBUTTONDOWN:
        MessageBox(
            NULL,
            (LPCWSTR)L"HALLOOOO",
            (LPCWSTR)L"Worked",
            MB_ICONASTERISK | MB_OK | MB_DEFBUTTON2
        );
        break;

but the problem is that this only works if the user clicks on the window and I want it to work even with the window minimized this work even if the application is minimized

GetKeyState(VK_LBUTTON);

but if I put this in a loop if I press it once it will detect 1 million times because it will just check if the key is down and if I add delay using Sleep(250) it may work but sometimes it will not detect anything even if the user pressed the key I want my app to be able to detect if a key is pressed even if it's minimized how can I do this?


Solution

  • Since you already have a window, call SetWindowsHookEx with WH_MOUSE_LL.

    The API is documented here and the parameters are explained.

    HHOOK SetWindowsHookExW(
      [in] int       idHook,
      [in] HOOKPROC  lpfn,
      [in] HINSTANCE hmod,
      [in] DWORD     dwThreadId
    );
    

    The lpfn hook procedure can be defined as follows:

    HWND hmain_window;
    HHOOK hhook;
    LRESULT CALLBACK mouse_proc(int code, WPARAM wparam, LPARAM lparam)
    {
        if (code == HC_ACTION && lparam) 
        {
            if (wparam == WM_LBUTTONDOWN)
            {
                //MOUSEHOOKSTRUCT* mstruct = (MOUSEHOOKSTRUCT*)lparam;
                static int i = 0;
                std::wstring str = L"mouse down " + std::to_wstring(i++);
                SetWindowText(hmain_window, str.c_str());
            }
        }
        return CallNextHookEx(hhook, code, wparam, lparam);
    }
    
    int APIENTRY wWinMain(HINSTANCE hinst, HINSTANCE, LPWSTR, int)
    {
        ...
        RegisterClassEx(...);
        hmain_window = CreateWindow(...);
        hhook = SetWindowsHookEx(WH_MOUSE_LL, mouse_proc, hinst, 0);
        MSG msg;
        while (GetMessage(&msg, NULL, 0, 0) > 0) 
        {
            TranslateMessage(&msg);
            DispatchMessage(&msg);
        }
        UnhookWindowsHookEx(hhook);
        return 0;
    }