C#注册全局热键

说明

热键 又名 快捷键组合键
作用为 响应键盘上的指定组合键, 做出相应的动作响应

原理

调用系统API

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
user32.dll.RegisterHotKey   // 注册热键
user32.dll.UnregisterHotKey // 注销热键

// 函数原型
BOOL WINAPI RegisterHotKey(
IntPtr hWnd, //要定义热键的窗口的句柄
int id, //定义热键ID(不能与其它ID重复)
KeyModifiers fsModifiers, //标识热键是否在按Alt、Ctrl、Shift、Windows等键时才会生效
Keys vk //定义热键的内容
);

BOOL WINAPI UnregisterHotKey(
IntPtr hWnd, //要取消热键的窗口的句柄
int id //要取消热键的ID
);


// 当热键命中时, 会给被注册的窗口发送"WM_HOTKEY" 消息
MSG msg = {0};
while (GetMessage(&msg, NULL, 0, 0) != 0)
{
if (msg.message == WM_HOTKEY)
{
_tprintf(_T("WM_HOTKEY received\n"));
}
}

enum KeyModifiers // 组合键, 多键组合 使用按位或上
{
None = 0, // 无作用
Alt = 1, // Alt按键
Ctrl = 2, // Ctrl 按键
Shift = 4, // Shift 按键
WindowsKey = 8 // Windows 按键
};

GlobalHotKey公共包

使用NuGet管理项目 引用“GlobalHotKey”
项目Git地址: GlobalHotKey

类说明

类名 作用
GlobalHotKey.HotKey 用于保存组合键内容
GlobalHotKey.HotKeyManager 用于管理组合键: 注册和响应热键
GlobalHotKey.KeyPressedEventArgs 响应热键时, 传入的参数, 为HotKey对象

GlobalHotKey包使用模版

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
// 引用 GlobalHotKey 包
using LibHotKey = GlobalHotKey; // 引用 GlobalHotKey 包
using SysInput = System.Windows.Input; // 系统键盘按键替代码

// 保存热键管理器对象, 生成热键对象
private LibHotKey.HotKeyManager m_objHotKeyManager = new LibHotKey.HotKeyManager();
private LibHotKey.HotKey m_objHotKey_Alt_Shift_H = new LibHotKey.HotKey()
{
Key = SysInput.Key.H,
Modifiers = SysInput.ModifierKeys.Shift | SysInput.ModifierKeys.Alt
};

// 注册热键
MessageBox.Show("注册热键");
try
{
m_objHotKeyManager.Register(m_objHotKey_Alt_Shift_H); //设置热键
m_objHotKeyManager.KeyPressed += HotKeyManagerPress; // 响应热键
}
except(Exception e)
{
// e.Message // 出现异常则为热键已占用

}


// 热键响应模版函数
private void HotKeyManagerPress(object sender, LibHotKey.KeyPressedEventArgs argEvent)
{
MessageBox.Show("热键命中");
if (argEvent.HotKey.Equals(m_objHotKey_Alt_Shift_H)) // 判断热键命中
{
MessageBox.Show("Shift+Alt+H");
}
}

// 注销热键
m_objHotKeyManager.Unregister(m_objHotKey_Alt_Shift_H);


// 注销以管理的全部热键
m_objHotKeyManager.Dispose()
文章目录
  1. 1. 说明
  2. 2. 原理
  3. 3. GlobalHotKey公共包
    1. 3.1. 类说明
    2. 3.2. GlobalHotKey包使用模版
|