tags:

views:

2108

answers:

2

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.

A: 

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

John T
+1  A: 

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;
}
Nick Whaley
Yep, that'll do it. Questions: (1) I see keys for the mouse X buttons, but not for the wheel. How to access? (2) What's the key enum name for the Windows key? (3) How do I output a given key combination back to the shell?
tsilb