註冊一個全區域的熱鍵,即是應用程式沒有被 focus 也能收到熱鍵。 網路上找到的通用類別,可輕易註冊想使用的 hotkey 然後自己寫對應的 handler using System; using windowcatch.ChatClient; using System.Runtime.InteropServices; namespace ChatClient { public delegate void HotkeyEventHandler(int HotKeyID); /// /// System wide hotkey wrapper. /// /// Robert Jeppesen /// Send bugs to robert@durius.com /// public class Hotkey : System.Windows.Forms.IMessageFilter { System.Collections.Hashtable keyIDs = new System.Collections.Hashtable(); IntPtr hWnd; /// /// Occurs when a hotkey has been pressed. /// public event HotkeyEventHandler OnHotkey; public enum KeyFlags { MOD_ALT = 0x1, MOD_CONTROL = 0x2, MOD_SHIFT = 0x4, MOD_WIN = 0x8 } [System.Runtime.InteropServices.DllImport("user32.dll")] public static extern UInt32 RegisterHotKey(IntPtr hWnd, UInt32 id, UInt32 fsModifiers, UInt32 vk); [System.Runtime.InteropServices.DllImport("user32.dll")] public static extern UInt32 UnregisterHotKey(IntPtr hWnd, UInt32 id); [System.Runtime.InteropServices.DllImport("kernel32.dll")] public static extern UInt32 GlobalAddAtom(String lpString); [System.Runtime.InteropServices.DllImport("kernel32.dll")] public static extern UInt32 GlobalDeleteAtom(UInt32 nAtom); /// /// Constructor. Adds this instance to the MessageFilters so that this class can raise Hotkey events /// /// A valid hWnd, i.e. form1.Handle public Hotkey(IntPtr hWnd) { this.hWnd = hWnd; System.Windows.Forms.Application.AddMessageFilter(this); } /// /// Register a system wide hotkey. /// /// form1.Handle /// Your hotkey /// ID integer for your hotkey. Use this to know which hotkey was pressed. public int RegisterHotkey(System.Windows.Forms.Keys Key, KeyFlags keyflags) { UInt32 hotkeyid = GlobalAddAtom(System.Guid.NewGuid().ToString()); RegisterHotKey((IntPtr)hWnd, hotkeyid, (UInt32)keyflags, (UInt32)Key); keyIDs.Add(hotkeyid, hotkeyid); return (int)hotkeyid; } /// /// Unregister hotkeys and delete atoms. /// public void UnregisterHotkeys() { System.Windows.Forms.Application.RemoveMessageFilter(this); foreach (UInt32 key in keyIDs.Values) { UnregisterHotKey(hWnd, key); GlobalDeleteAtom(key); } } public bool PreFilterMessage(ref System.Windows.Forms.Message m) { if (m.Msg == 0x312) /*WM_HOTKEY*/ { if (OnHotkey != null) { foreach (UInt32 key in keyIDs.Values) { if ((UInt32)m.WParam == key) { OnHotkey((int)m.WParam); return true; } } } } return false; } } }
使用方法很簡單 Hotkey hotkey; // 宣告類別 hotkey = new Hotkey(this.Handle); // 指定 this.Handle 給 hotkey 類別 int Hotkey1 = hotkey.RegisterHotkey(System.Windows.Forms.Keys.D1, Hotkey.KeyFlags.MOD_CONTROL); // 註冊 ctrl+1 為全域熱鍵 hotkey.OnHotkey += new HotkeyEventHandler(OnHotkey); // 指定熱鍵發生時的 handle function 接下來只要寫好 OnHotkey 要處理的事情就好。
