C#: How to capture global mouse/HID events

2019-06-09 21:43发布

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.

标签: c# hotkeys
2条回答
Anthone
2楼-- · 2019-06-09 22:25

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;
}
查看更多
啃猪蹄的小仙女
3楼-- · 2019-06-09 22:31

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

查看更多
登录 后发表回答