KeyEventsHelper.cs 2.9 KB

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