首先,引用using System.Runtime.InteropServices;
using System.Runtime.InteropServices;
其次,声明API函数,分别为RegisterHotKey(注册热键)和UnregisterHotKey(卸载热键)
[DllImport("user32.dll")]
public static extern bool RegisterHotKey(
IntPtr hWnd, //handle to winfow
int id, //hot key identifer
uint fsModifiers, // key-modifier options
Keys vk //virtual-key code
);
[DllImport("user32.dll")]
public static extern bool UnregisterHotKey(
IntPtr hWnd, //handle to winfow
int id //hot key identifer
);
然后,定义枚举
public enum KeyModifiers
{
None = 0,
Alt = 1,
Control = 2,
Shift = 4,
Windows = 8
}
之后,重写WndProc事件,并定义相应的点击事件
protected override void WndProc(ref Message m)
{
//如果m.Msg的值为0x0312,则表示用户按下了热键
const int WM_HOTKEY = 0x0312;
switch (m.Msg)
{
case WM_HOTKEY:
ProcessHotKey(m);
break;
}
base.WndProc(ref m);
}
最后,在Form加载页面或者构造函数中根据需求注册热键,在关闭Form之前卸载热键,即可。
public Form2()
{
InitializeComponent();
//注册HotKey
RegisterHotKey(Handle, 100, 1, Keys.D1);//Alt + 1
RegisterHotKey(Handle, 200, 1, Keys.D2);//Alt + 2
RegisterHotKey(Handle, 300, 2, Keys.D2);//Control + 2
}
private void Form2_BeforeClose(object sender, FormClosingEventArgs e)
{
UnregisterHotKey(Handle, 100);
UnregisterHotKey(Handle, 200);
UnregisterHotKey(Handle, 300);
}
编写时主要参考了这篇博客——C# WinForm程序中使用热键(HotKey)_代码世界-CSDN博客_winform 系统热键