using System.Runtime.InteropServices;
[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
{
None = 0,
Alt = 1,
Control = 2,
Shift = 4,
Windows = 8
}
可透過位元運算組合:Control | Shift = 6
public MainForm()
{
InitializeComponent();
RegisterHotKey(Handle, 100, 2, Keys.Left); // Ctrl + Left
RegisterHotKey(Handle, 200, 2, Keys.Right); // Ctrl + Right
RegisterHotKey(Handle, 300, 2, Keys.Up); // Ctrl + Up
RegisterHotKey(Handle, 400, 2, Keys.Down); // Ctrl + Down
}
protected override void WndProc(ref Message m)
{
const int WM_HOTKEY = 0x0312;
switch (m.Msg)
{
case WM_HOTKEY:
ProcessHotkey(m);
break;
}
base.WndProc(ref m);
}
private void ProcessHotkey(Message m)
{
IntPtr id = m.WParam;
string sid = id.ToString();
switch (sid)
{
case "100": DecreaseVolume(); break; // Ctrl + Left
case "200": IncreaseVolume(); break; // Ctrl + Right
case "300": this.Visible = true; break; // Ctrl + Up
case "400": this.Visible = false; break; // Ctrl + Down
}
}
private void MainForm_FormClosing(object sender, FormClosingEventArgs e)
{
UnregisterHotKey(Handle, 100);
UnregisterHotKey(Handle, 200);
UnregisterHotKey(Handle, 300);
UnregisterHotKey(Handle, 400);
}
System.Runtime.InteropServicesDllImport 宣告 RegisterHotKey/UnregisterHotKeyKeyModifiers 列舉支援組合鍵WndProc 攔截 WM_HOTKEY (0x0312)ProcessHotkey 依 ID 分派功能FormClosing 中全部註銷false) 通常因熱鍵已被其他程式佔用