HotKey.cs 2.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Runtime.InteropServices;
  4. using System.Windows;
  5. using System.Windows.Input;
  6. using System.Windows.Interop;
  7. /// <summary>
  8. /// 热键注册
  9. /// </summary>
  10. namespace GeekDesk.Util
  11. {
  12. class Hotkey
  13. {
  14. #region 系统api
  15. [DllImport("user32.dll")]
  16. [return: MarshalAs(UnmanagedType.Bool)]
  17. static extern bool RegisterHotKey(IntPtr hWnd, int id, HotkeyModifiers fsModifiers, uint vk);
  18. [DllImport("user32.dll")]
  19. static extern bool UnregisterHotKey(IntPtr hWnd, int id);
  20. #endregion
  21. /// <summary>
  22. /// 注册快捷键
  23. /// </summary>
  24. /// <param name="window">持有快捷键窗口</param>
  25. /// <param name="fsModifiers">组合键</param>
  26. /// <param name="key">快捷键</param>
  27. /// <param name="callBack">回调函数</param>
  28. public static int Regist(IntPtr windowHandle, HotkeyModifiers fsModifiers, Key key, HotKeyCallBackHanlder callBack)
  29. {
  30. HwndSource hs = HwndSource.FromHwnd(windowHandle);
  31. hs.AddHook(WndProc);
  32. int id = keyid++;
  33. int vk = KeyInterop.VirtualKeyFromKey(key);
  34. keymap.Add(id, callBack);
  35. if (!RegisterHotKey(windowHandle, id, fsModifiers, (uint)vk)) throw new Exception("RegisterHotKey Failed");
  36. return id;
  37. }
  38. /// <summary>
  39. /// 快捷键消息处理
  40. /// </summary>
  41. static IntPtr WndProc(IntPtr windowHandle, int msg, IntPtr wParam, IntPtr lParam, ref bool handled)
  42. {
  43. if (msg == WM_HOTKEY)
  44. {
  45. int id = wParam.ToInt32();
  46. if (keymap.TryGetValue(id, out var callback))
  47. {
  48. callback();
  49. }
  50. }
  51. return IntPtr.Zero;
  52. }
  53. /// <summary>
  54. /// 注销快捷键
  55. /// </summary>
  56. /// <param name="hWnd">持有快捷键窗口的句柄</param>
  57. /// <param name="callBack">回调函数</param>
  58. public static void UnRegist(IntPtr windowHandle, HotKeyCallBackHanlder callBack)
  59. {
  60. List<int> list = new List<int>(keymap.Keys);
  61. for (int i=0; i < list.Count; i++)
  62. {
  63. if (keymap[list[i]] == callBack)
  64. {
  65. HwndSource hs = HwndSource.FromHwnd(windowHandle);
  66. hs.RemoveHook(WndProc);
  67. UnregisterHotKey(windowHandle, list[i]);
  68. keymap.Remove(list[i]);
  69. }
  70. }
  71. }
  72. const int WM_HOTKEY = 0x312;
  73. static int keyid = 10;
  74. public static Dictionary<int, HotKeyCallBackHanlder> keymap = new Dictionary<int, HotKeyCallBackHanlder>();
  75. public delegate void HotKeyCallBackHanlder();
  76. }
  77. public enum HotkeyModifiers
  78. {
  79. MOD_ALT = 0x1,
  80. MOD_CONTROL = 0x2,
  81. MOD_SHIFT = 0x4,
  82. MOD_WIN = 0x8
  83. }
  84. }