系統熱鍵 (Hotkey) 讓應用程式在無焦點時也能接收特定鍵盤組合 (如 Ctrl+Alt+F1)。本文示範使用 P/Invoke 呼叫 user32.dll 的 RegisterHotKey/UnregisterHotKey,並在 WndProc 處理 WM_HOTKEY 訊息。
using System;
using System.Runtime.InteropServices;
using System.Windows.Forms;
public partial class MainForm : Form
{
[DllImport("user32.dll")]
public static extern bool RegisterHotKey(IntPtr hWnd, int id, uint fsModifiers, Keys vk);
[DllImport("user32.dll")]
public static extern bool UnregisterHotKey(IntPtr hWnd, int id);
// 修飾鍵旗標
public enum KeyModifiers : uint
{
None = 0, Alt = 1, Control = 2, Shift = 4, Windows = 8
}
public MainForm()
{
InitializeComponent();
// 註冊四組熱鍵:Ctrl + 方向鍵
RegisterHotKey(Handle, 100, (uint)KeyModifiers.Control, Keys.Left); // 音量-
RegisterHotKey(Handle, 200, (uint)KeyModifiers.Control, Keys.Right); // 音量+
RegisterHotKey(Handle, 300, (uint)KeyModifiers.Control, Keys.Up); // 顯示視窗
RegisterHotKey(Handle, 400, (uint)KeyModifiers.Control, Keys.Down); // 隱藏視窗
}
protected override void WndProc(ref Message m)
{
const int WM_HOTKEY = 0x0312;
if (m.Msg == WM_HOTKEY)
{
ProcessHotkey(m);
return; // 處理完直接返回,不傳遞給基類
}
base.WndProc(ref m);
}
private void ProcessHotkey(Message m)
{
int id = m.WParam.ToInt32(); // 熱鍵 ID
switch (id)
{
case 100: DecreaseVolume(); break;
case 200: IncreaseVolume(); break;
case 300: this.Visible = true; break;
case 400: this.Visible = false; break;
}
}
private void MainForm_FormClosing(object sender, FormClosingEventArgs e)
{
UnregisterHotKey(Handle, 100);
UnregisterHotKey(Handle, 200);
UnregisterHotKey(Handle, 300);
UnregisterHotKey(Handle, 400);
}
GlobalAddAtom 產生唯一原子 ID。fsModifiers 可位元組合 (如 Control | Alt = 3)。RegisterHotKey 回傳 false,需提示使用者更換組合。InputBindings、全域鍵盤 Hook (LowLevelKeyboardProc) 功能更強但複雜度高。系統熱鍵是打造常駐系統匣、快速啟動工具、媒體播放器控制等應用的關鍵技術。正確實作註冊/解除註冊、訊息處理、錯誤處理,能讓熱鍵功能穩定可靠。本文提供的完整範例可直接整合至 WinForms 專案中使用。