全局快捷键的使用
使用全局快捷键后,可以不切换到WPF窗口即可执行该窗口中的一些操作
需要添加的引用
using System.Runtime.InteropServices;
using System.Windows.Interop;
声明的相应代码
1 static class Hotkey
2 {
3 #region 系统api
4 [DllImport("user32.dll")]
5 [return: MarshalAs(UnmanagedType.Bool)]
6 static extern bool RegisterHotKey(IntPtr hWnd, int id, HotkeyModifiers fsModifiers, uint vk);
7
8 [DllImport("user32.dll")]
9 static extern bool UnregisterHotKey(IntPtr hWnd, int id);
10 #endregion
11
12
13
14
15
16
17
18
19 public static void Regist(Window window, HotkeyModifiers fsModifiers, Key key, HotKeyCallBackHanlder callBack)
20 {
21 var hwnd = new WindowInteropHelper(window).Handle;
22 var _hwndSource = HwndSource.FromHwnd(hwnd);
23 _hwndSource.AddHook(WndProc);
24
25 int id = keyid++;
26
27 var vk = KeyInterop.VirtualKeyFromKey(key);
28 if (!RegisterHotKey(hwnd, id, fsModifiers, (uint)vk))
29 throw new Exception("regist hotkey fail.");
30 keymap[id] = callBack;
31 }
32
33
34
35
36 static IntPtr WndProc(IntPtr hwnd, int msg, IntPtr wParam, IntPtr lParam, ref bool handled)
37 {
38 if (msg == WM_HOTKEY)
39 {
40 int id = wParam.ToInt32();
41 if (keymap.TryGetValue(id, out var callback))
42 {
43 callback();
44 }
45 }
46 return IntPtr.Zero;
47 }
48
49
50
51
52
53
54 public static void UnRegist(IntPtr hWnd, HotKeyCallBackHanlder callBack)
55 {
56 foreach (KeyValuePair<int, HotKeyCallBackHanlder> var in keymap)
57 {
58 if (var.Value == callBack)
59 UnregisterHotKey(hWnd, var.Key);
60 }
61 }
62
63
64 const int WM_HOTKEY = 0x312;
65 static int keyid = 10;
66 static Dictionary<int, HotKeyCallBackHanlder> keymap = new Dictionary<int, HotKeyCallBackHanlder>();
67
68 public delegate void HotKeyCallBackHanlder();
69 }
70
71 enum HotkeyModifiers
72 {
73 MOD_ALT = 0x1,
74 MOD_CONTROL = 0x2,
75 MOD_SHIFT = 0x4,
76 MOD_WIN = 0x8
77 }
2种调用方式
重写函数来注册
protect override void OnSourceInitialized(EventArgs e)
{
Hotkey.Regist(this, HotkeyModifiers.MOD_ALT, Key.T,()=>
{
MessageBox.Show("hello");
MessageBox.Show(this,"hello");
})
}
在Load中来注册
private void Window_Loaded(object sender, RoutedEventArgs e)
{
Hotkey.Regist(this, HotkeyModifiers.MOD_ALT, Key.T,()=>
{
MessageBox.Show("hello");
MessageBox.Show(this,"hello");
})
}