HotKeyManager.cs 2.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. using System.Windows;
  2. using System.Windows.Input;
  3. using KeyEventHandler = System.Windows.Input.KeyEventHandler;
  4. namespace InABox.WPF
  5. {
  6. public enum HotKeyModifier
  7. {
  8. Ctrl,
  9. Shift,
  10. Alt
  11. }
  12. public static class HotKeyManager
  13. {
  14. private static readonly List<Tuple<Key, HotKeyModifier[], Func<bool>>> _hotkeys = new();
  15. private static Tuple<Key, HotKeyModifier[], Func<bool>> FindHotKey(Key key, HotKeyModifier[] modifiers)
  16. {
  17. var m = modifiers != null ? modifiers : new HotKeyModifier[] { };
  18. var existing = _hotkeys.FirstOrDefault(
  19. x => x.Item1 == key && x.Item2.Length == m.Length && x.Item2.Intersect(m).Count() == x.Item2.Length);
  20. return existing;
  21. }
  22. public static void RegisterHotKey(Key key, Func<bool> action)
  23. {
  24. RegisterHotKey(key, new HotKeyModifier[] { }, action);
  25. }
  26. public static void RegisterHotKey(Key key, HotKeyModifier[] modifiers, Func<bool> action)
  27. {
  28. var existing = FindHotKey(key, modifiers);
  29. if (existing != null)
  30. throw new Exception(string.Format("HotKey [{0}+{1}] is already registered!", string.Join("+", modifiers.Select(x => x)), key));
  31. _hotkeys.Add(new Tuple<Key, HotKeyModifier[], Func<bool>>(key, modifiers, action));
  32. }
  33. public static void UnRegisterHotKey(Key key)
  34. {
  35. UnRegisterHotKey(key, new HotKeyModifier[] { });
  36. }
  37. public static void UnRegisterHotKey(Key key, HotKeyModifier[] modifiers)
  38. {
  39. var existing = FindHotKey(key, modifiers);
  40. if (existing != null)
  41. _hotkeys.Remove(existing);
  42. }
  43. public static bool ProcessHotKey(Key key)
  44. {
  45. var modifiers = new List<HotKeyModifier>();
  46. if (Keyboard.IsKeyDown(Key.LeftShift) || Keyboard.IsKeyDown(Key.RightShift))
  47. modifiers.Add(HotKeyModifier.Shift);
  48. if (Keyboard.IsKeyDown(Key.LeftCtrl) || Keyboard.IsKeyDown(Key.RightCtrl))
  49. modifiers.Add(HotKeyModifier.Ctrl);
  50. if (Keyboard.IsKeyDown(Key.LeftAlt) || Keyboard.IsKeyDown(Key.RightAlt))
  51. modifiers.Add(HotKeyModifier.Alt);
  52. var existing = FindHotKey(key, modifiers.ToArray());
  53. if (existing != null)
  54. return existing.Item3.Invoke();
  55. return false;
  56. }
  57. public static void Initialize()
  58. {
  59. EventManager.RegisterClassHandler(
  60. typeof(Window),
  61. Keyboard.KeyDownEvent,
  62. new KeyEventHandler(
  63. (o, args) =>
  64. {
  65. ProcessHotKey(args.Key);
  66. //args.Handled = args.Key == Key.Space ? true : ProcessHotKey(args.Key);
  67. }
  68. ),
  69. true
  70. );
  71. }
  72. }
  73. }