HotKeyManager.cs 3.0 KB

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