核心 API
RegisterHotKey(hWnd, id, fsModifiers, vk):註冊熱鍵,fsModifiers 為輔助鍵 (Alt/Ctrl/Shift/Win),vk 為虛擬鍵碼。
UnregisterHotKey(hWnd, id):註銷。
- 在
WndProc 攔截 WM_HOTKEY (0x0312),依 WParam (id) 判斷觸發哪個熱鍵。
完整代碼
public partial class Form1 : Form {
public Form1() {
InitializeComponent();
HotKey.RegisterHotKey(this.Handle, 100, HotKey.KeyModifiers.None, Keys.F1);
}
protected override void WndProc(ref Message m) {
const int WM_HOTKEY = 0x0312;
if (m.Msg == WM_HOTKEY && m.WParam.ToInt32() == 100) {
MessageBox.Show("Press F1");
}
base.WndProc(ref m);
}
}
public class HotKey {
[DllImport("user32.dll", SetLastError = true)]
public static extern bool RegisterHotKey(IntPtr hWnd, int id, KeyModifiers fsModifiers, Keys vk);
[DllImport("user32.dll", SetLastError = true)]
public static extern bool UnregisterHotKey(IntPtr hWnd, int id);
[Flags]
public enum KeyModifiers { None = 0, Alt = 1, Ctrl = 2, Shift = 4, WindowsKey = 8 }
}
注意事項
id 全進程唯一,避免衝突。
- 表單關閉時務必呼叫
UnregisterHotKey。
- 若熱鍵被其他程式佔用,註冊會失敗 (回傳 false),可檢查
Marshal.GetLastWin32Error()。