2011-01-20 123 views
0

我被卡住了。在.NET中註冊熱鍵 - 三鍵/四鍵組合

現在,我使用下面的代碼來聽熱鍵:

[DllImport("user32.dll")] 
    public static extern bool RegisterHotKey(IntPtr hWnd, 
     int id, int fsModifiers, int vlc); 
    [DllImport("user32.dll")] 
    public static extern bool UnregisterHotKey(IntPtr hWnd, int id); 


    protected override void WndProc(ref Message m) 
    { 
     if (m.Msg == 0x0312) 
     { 
      // whatever i need 
     } 
     base.WndProc(ref m); 
    } 

這個函數註冊熱鍵:

Form1.RegisterHotKey(this.Handle, this.GetType().GetHashCode(), 0, (int)chr); 

它完美的作品。 我的問題是如何註冊多個熱鍵爲相同的組合,例如:

  1. A + B + C + d
  2. ALT + SHIFT + B
  3. Ctrl + Alt + SHIFT + X

編輯:我發現(如Zooba說)如何「解密」的熱鍵被送到這裏的解決方案:

protected override void WndProc(ref Message m) 
    { 
     if (m.Msg == 0x0312) 
     { 
      Keys key = (Keys)(((int)m.LParam >> 16) & 0xFFFF); 
      ModifierKeys modifier = (ModifierKeys)((int)m.LParam & 0xFFFF); 
      if ((modifier + "+" + key == "Alt+S")) 
      { 
       //do what ever I need. 
      } 
     } 
     base.WndProc(ref m); 
    } 
+0

爲什麼不是更有野心,去5或6組合鍵? – 2011-01-20 21:18:19

+0

[RegisterHotKey註冊多個熱鍵](http:// stackoverflow。com/questions/4704134/register-more-one-hotkey-with-registerhotkey) – 2011-01-20 21:38:32

+0

@David Heffernan,我會選擇5或6個組合鍵,但windows不允許同時點擊4個以上的鍵: P.無論如何,我只想涵蓋所有選項... – Ron 2011-01-20 21:56:12

回答

0

我找到了答案。我沒有使用registerhotkey,而是使用KeyState,它解決了我所有的問題。如果有人有興趣,你可以go herebackup on archive.org

4

從文檔WM_HOTKEY

lParam的的低位字指定爲組合被壓與由高位字以生成WM_HOTKEY消息中指定的鍵的鍵。這個詞可以是以下一個或多個值。高位字指定熱鍵的虛擬鍵碼。

所以,你可以閱讀的mLParam成員,以確定被按下的鍵(或者,如果您分配更明智的標識符比GetHashCode你可以檢查WParam)。

「高位字」和「低位字」是指LParam中包含的整數部分(實際上是IntPtr),所以您需要提取這些字符。低位字是i & 0xFFFF,而高位字是(i >> 16) & 0xFFFF

要檢測按下哪個組合鍵,請檢查低位字的最低四位(修飾符,shift,alt,control),並將高位字與虛擬鍵碼進行比較 - 對於字母是等於資本的字符值(例如,A的虛擬鍵碼是(int)'A',但不是(int)'a')。

您的'A + B + C + D'組合無效,因爲WM_HOTKEY熱鍵只支持單個字符。您需要附加鍵盤掛鉤才能從任何地方檢測到該組合(或者如果您只希望在應用程序處於活動狀態時檢測它,則可處理消息)。