2009-04-14 134 views
0

我希望編寫一個小工具來捕獲全局事件,當用戶按下Windows按鈕並向上或向下滾動鼠標滾輪時。當捕獲這樣的事件時,我希望將所述輸出重定向到Win- +或Win-(加/減)的虛擬擊鍵組合。這可以做到嗎?C#:如何捕捉全局鼠標/ HID事件

如果Windows鍵被保留,ctrl-alt或類似的。

回答

1

由於它使用Windows密鑰,可以使用熱鍵綁定全局捕獲密鑰。 RegisterHotKey msdn

編輯:似乎mousewheel事件不被視爲鍵,因爲我認爲,並沒有辦法爲他們做全球熱鍵。

您將不得不作出全局窗口消息掛鉤並捕獲WM_MOUSEWHEEL消息。但是你可能必須在C/C++中做到這一點。下面是一個C DLL的完成,你可以從C#中調用Hook和Unhook來啓用和禁用該功能。

警告:我沒有測試此代碼,僅作爲演示提供。

#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; 
} 
+0

是的,這將做到這一點。問題:(1)我看到鼠標X按鈕的按鍵,但不是輪子。如何訪問? (2)Windows鍵的鍵枚舉名是什麼? (3)如何將給定的組合鍵輸出到shell中? – tsilb 2009-04-14 03:26:46

0

它絕對可以通過全局鉤子完成,here是一個很好的CodeProject示例。