C#: How to capture global mouse/HID events

≡放荡痞女 提交于 2020-01-24 01:32:07

问题


I wish to write a small tool that will capture a global event when the user presses the Windows button and scrolls the mousewheel up or down. When such an event is captured, I wish to redirect said output to a virtual keystroke combination of Win-+ or Win-- (plus/minus). Can this be done?

If the windows key is reserved, ctrl-alt or such would do.


回答1:


Since it uses the windows key, the key can be captured globally using a hotkey binding. RegisterHotKey at msdn.

Edit: It seems the mousewheel events are not treated as keys as I assumed and there is no way to make a global hotkey for them.

You will have to make a global window message hook and trap the WM_MOUSEWHEEL message. But you may have to do that in C/C++. A C dll to accomplish this is below, you can call Hook and Unhook from C# to enable and disable the function.

WARNING: I have not tested this code and is provided as a demonstration only.

#include <windows.h>

HINSTANCE myInstance;
HHOOK thehook = 0;
BOOL isWinKeyDown = FALSE;

extern "C" LRESULT __declspec(dllexport)__stdcall CALLBACK HookHandler(int nCode, WPARAM wParam, LPARAM lParam) {
    if (nCode == WM_KEYDOWN && (wParam == VK_LWIN || wParam == VK_RWIN))
        isWinKeyDown = TRUE;
    else if (nCode == WM_KEYUP && (wParam == VK_LWIN || wParam == VK_RWIN))
        isWinKeyDown = FALSE;
    else if (nCode == WM_MOUSEHWHEEL && isWinKeyDown) {
        if (HIWORD(wParam) > 0) { //mousewheel up
            CallNextHookEx(thehook, WM_KEYDOWN, VK_ADD, 0);
            CallNextHookEx(thehook, WM_KEYUP, VK_ADD, 0);
        } else { //mousewheel down
            CallNextHookEx(thehook, WM_KEYDOWN, VK_SUBTRACT, 0);
            CallNextHookEx(thehook, WM_KEYUP, VK_SUBTRACT, 0);
        }
        return 0;
    }
    return CallNextHookEx(thehook, nCode, wParam, lParam);
}
BOOL WINAPI DllMain(HINSTANCE hInstance, DWORD fwdReason, LPVOID lpvReserved) {
    switch(fwdReason)
    {
        case DLL_PROCESS_ATTACH: {
            DisableThreadLibraryCalls(hInstance);
            myInstance = hInstance;

            } break;
        case DLL_THREAD_ATTACH:
            break;
        case DLL_PROCESS_DETACH:

            break;
        case DLL_THREAD_DETACH:
            break;
    }
    return(TRUE);               // The initialization was successful, a FALSE will abort
                                // the DLL attach
}

extern "C" void __declspec(dllexport) Hook() {
    if (!thehook)
        thehook = SetWindowsHookEx(WH_CALLWNDPROC, &HookHandler, myInstance, 0);
}
extern "C" void __declspec(dllexport) UnHook() {
    if (thehook)
        UnhookWindowsHookEx(thehook);
    thehook = 0;
}



回答2:


It can definitely be done via global hooks, here is a great CodeProject example on how to do so.



来源:https://stackoverflow.com/questions/746188/c-how-to-capture-global-mouse-hid-events

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