-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathHotKeys.cs
81 lines (70 loc) · 1.82 KB
/
HotKeys.cs
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
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
using System;
using System.Collections.Generic;
using System.Runtime.InteropServices;
using System.Windows.Forms;
namespace MouseSwitcher
{
public class HotKeys
{
public delegate void HotKeyCallBackHanlder();
public static string GetKeyName(HotkeyModifiers key)
{
return key switch
{
HotkeyModifiers.Alt => "Alt",
HotkeyModifiers.Control => "Ctrl",
HotkeyModifiers.Shift => "Shift",
HotkeyModifiers.Win => "Win",
_ => "UNKNOWN_" + ((int)key).ToString(),
};
}
public static string GetKeyName(Keys key)
{
return Enum.GetName(typeof(Keys), key);
}
public enum HotkeyModifiers
{
Alt = 1,
Control = 2,
Shift = 4,
Win = 8
}
public int keyid = 10;
private Dictionary<int, HotKeyCallBackHanlder> keymap = new Dictionary<int, HotKeyCallBackHanlder>();
[DllImport("user32.dll")]
private static extern bool RegisterHotKey(IntPtr hWnd, int id, int modifiers, Keys vk);
[DllImport("user32.dll")]
private static extern bool UnregisterHotKey(IntPtr hWnd, int id);
public void Regist(IntPtr hWnd, HotkeyModifiers modifiers, Keys vk, HotKeyCallBackHanlder callBack)
{
int num = keyid++;
if (!RegisterHotKey(hWnd, num, (int)modifiers, vk))
{
throw new Exception("注册失败!");
}
keymap[num] = callBack;
}
public void UnRegist(IntPtr hWnd, HotKeyCallBackHanlder callBack)
{
foreach (KeyValuePair<int, HotKeyCallBackHanlder> item in keymap)
{
if (item.Value == callBack)
{
UnregisterHotKey(hWnd, item.Key);
break;
}
}
}
public void ProcessHotKey(Message m)
{
if (m.Msg == 786)
{
int key = m.WParam.ToInt32();
if (keymap.TryGetValue(key, out var value))
{
value();
}
}
}
}
}