KeyEventsHelper.cs 3.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using System.Threading.Tasks;
  6. using System.Windows;
  7. using System.Windows.Controls;
  8. using System.Windows.Input;
  9. namespace PDF_Office.Helper
  10. {
  11. //全局快捷键响应
  12. public static class KeyEventsHelper
  13. {
  14. #region Todo 快捷键绑定解绑在其他地方使用
  15. //绑定:KeyEventsHelper.KeyDown += ShortCut_KeyDown;
  16. //解绑:KeyEventsHelper.KeyDown -= ShortCut_KeyDown;
  17. #endregion Todo 快捷键绑定解绑在其他地方使用
  18. public static event EventHandler<KeyEventArgs> KeyDown;
  19. private static KeyEventArgs args;
  20. static KeyEventsHelper()
  21. {
  22. EventManager.RegisterClassHandler(typeof(Window), UIElement.KeyDownEvent, (KeyEventHandler)onKeyDown);
  23. EventManager.RegisterClassHandler(typeof(ContextMenu), UIElement.KeyDownEvent, (KeyEventHandler)onKeyDown);
  24. }
  25. private static void onKeyDown(object sender, KeyEventArgs e)
  26. {
  27. if (e != null)
  28. {
  29. args = e;
  30. KeyDown?.Invoke(sender, e);
  31. }
  32. }
  33. /// <summary>
  34. /// 按下单一键,例如:只按下H有效;同时按下其他修饰键如ctrl等无效
  35. /// </summary>
  36. public static bool IsSingleKey(Key currentkey)
  37. {
  38. if(args == null) return false;
  39. if (args.Key == currentkey && args.KeyboardDevice.Modifiers == ModifierKeys.None)
  40. {
  41. return true;
  42. }
  43. return false;
  44. }
  45. /// <summary>
  46. /// 组合键 = 修饰键+序列键
  47. /// 例如:同时按下Ctrl + H 或(同时按下Ctrl + [Key=None无任何键]),同时再按下其他修饰键则无响应
  48. /// </summary>
  49. public static bool IsModifierKey(ModifierKeys modifier, Key currentkey)
  50. {
  51. if (args == null) return false;
  52. if (args.Key == currentkey && args.KeyboardDevice.Modifiers == modifier)
  53. {
  54. return true;
  55. }
  56. return false;
  57. }
  58. /// <summary>
  59. /// 例如:按下此键外,再按下其他键也响应(不常用,特殊处理)
  60. /// </summary>
  61. public static bool IsKeyDown(Key currentkey)
  62. {
  63. if (args == null) return false;
  64. if (Keyboard.IsKeyDown(currentkey))
  65. {
  66. return true;
  67. }
  68. return false;
  69. }
  70. /// <summary>
  71. /// 例如:同时按下一个或多个键外,再按下其他键也响应(不常用,特殊处理)
  72. /// </summary>
  73. public static bool IsKeyDown(List<Key> keys)
  74. {
  75. if (args == null || keys == null || keys.Count > 0) return false;
  76. bool result = false;
  77. foreach (Key key in keys)
  78. {
  79. result |= Keyboard.IsKeyDown(key);
  80. }
  81. if (result)
  82. {
  83. return true;
  84. }
  85. return false;
  86. }
  87. }
  88. }