透過 P/Invoke 呼叫 user32.dll 的 RegisterHotKey 與 UnregisterHotKey,在 WinForms 應用程式中註冊系統層級熱鍵,即使視窗未具焦點也能觸發。
using System;
using System.Runtime.InteropServices;
using System.Windows.Forms;
public partial class HotKeyForm : Form
{
// 匯入 API
[DllImport("user32.dll")]
private static extern bool RegisterHotKey(IntPtr hWnd, int id, uint fsModifiers, Keys vk);
[DllImport("user32.dll")]
private static extern bool UnregisterHotKey(IntPtr hWnd, int id);
// 修飾鍵列舉
private enum KeyModifiers : uint
{
None = 0,
Alt = 1,
Control = 2,
Shift = 4,
Windows = 8
}
private const int WM_HOTKEY = 0x0312;
private const int HOTKEY_ID_1 = 100;
private const int HOTKEY_ID_2 = 200;
public HotKeyForm()
{
InitializeComponent();
}
protected override void WndProc(ref Message m)
{
if (m.Msg == WM_HOTKEY)
{
int id = m.WParam.ToInt32();
switch (id)
{
case HOTKEY_ID_1:
MessageBox.Show("觸發熱鍵 1 (Ctrl+A)");
break;
case HOTKEY_ID_2:
MessageBox.Show("觸發熱鍵 2 (Ctrl+B)");
break;
}
}
base.WndProc(ref m);
}
private void HotKeyForm_Load(object sender, EventArgs e)
{
// 註冊 Ctrl+A 與 Ctrl+B
RegisterHotKey(Handle, HOTKEY_ID_1, (uint)KeyModifiers.Control, Keys.A);
RegisterHotKey(Handle, HOTKEY_ID_2, (uint)KeyModifiers.Control, Keys.B);
}
private void HotKeyForm_FormClosing(object sender, FormClosingEventArgs e)
{
// 卸載熱鍵
UnregisterHotKey(Handle, HOTKEY_ID_1);
UnregisterHotKey(Handle, HOTKEY_ID_2);
}
private void btnResetHotkey_Click(object sender, EventArgs e)
{
UnregisterHotKey(Handle, HOTKEY_ID_1);
RegisterHotKey(Handle, HOTKEY_ID_1, (uint)KeyModifiers.Control, Keys.C); // 改為 Ctrl+C
}
}
Alt | Control 代表 Alt+Ctrl。FormClosing 卸載熱鍵,否則系統保留導致重複註冊失敗。WndProc 攔截 WM_HOTKEY 訊息處理觸發邏輯。
應用場景: 螢幕截圖工具、快速啟動器、媒體播放器控制。