即使应用程序最小化,也为鼠标按钮创建事件

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

我想制作一个响应鼠标按钮的应用程序,所以我这样做了:

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

但问题是,这仅在用户单击 window 时才有效,我希望它即使在 window 最小化的情况下也能正常工作 即使应用程序最小化也能正常工作

GetKeyState(VK_LBUTTON);

但是如果我把它放在一个循环中,如果我按下它一次,它会检测到 100 万次,因为它只会检查按键是否按下,如果我使用 Sleep(250) 添加延迟,它可能会起作用,但有时即使用户按下键也不会检测到任何东西 我希望我的应用能够检测是否按下了某个键,即使它已最小化我该怎么做?

您可以尝试使用 SetWindowsHookEx 参数 WH_MOUSE_LL 或 WH_MOUSE。

This article shows how to install a keyboard hook. You can replace WH_KEYBOARD with WH_MOUSE to install a mouse hook and use this document 处理回调。

因为你已经有了一个 window,请用 WH_MOUSE_LL 调用 SetWindowsHookEx

对API进行了说明here并对参数进行了说明

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

lpfn钩子程序可以定义如下:

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