using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows; using System.Windows.Controls; using System.Windows.Input; namespace PDF_Master.Helper { //全局快捷键响应 public static class KeyEventsHelper { #region Todo 快捷键绑定解绑在其他地方使用 //绑定:KeyEventsHelper.KeyDown += ShortCut_KeyDown; //解绑:KeyEventsHelper.KeyDown -= ShortCut_KeyDown; #endregion Todo 快捷键绑定解绑在其他地方使用 public static event EventHandler KeyDown; private static KeyEventArgs args; static KeyEventsHelper() { EventManager.RegisterClassHandler(typeof(Window), UIElement.KeyDownEvent, (KeyEventHandler)onKeyDown); EventManager.RegisterClassHandler(typeof(ContextMenu), UIElement.KeyDownEvent, (KeyEventHandler)onKeyDown); } private static void onKeyDown(object sender, KeyEventArgs e) { if (e != null) { args = e; KeyDown?.Invoke(sender, e); } } /// /// 按下单一键,例如:只按下H有效;同时按下其他修饰键如ctrl等无效 /// public static bool IsSingleKey(Key currentkey) { if(args == null) return false; if (args.Key == currentkey && args.KeyboardDevice.Modifiers == ModifierKeys.None) { return true; } return false; } /// /// 组合键 = 修饰键+序列键 /// 例如:同时按下Ctrl + H 或(同时按下Ctrl + [Key=None无任何键]),同时再按下其他修饰键则无响应 /// public static bool IsModifierKey(ModifierKeys modifier, Key currentkey) { if (args == null) return false; if (args.Key == currentkey && args.KeyboardDevice.Modifiers == modifier) { return true; } return false; } /// /// 例如:按下此键外,再按下其他键也响应(不常用,特殊处理) /// public static bool IsKeyDown(Key currentkey) { if (args == null) return false; if (Keyboard.IsKeyDown(currentkey)) { return true; } return false; } /// /// 例如:同时按下一个或多个键外,再按下其他键也响应(不常用,特殊处理) /// public static bool IsKeyDown(List keys) { if (args == null || keys == null || keys.Count > 0) return false; bool result = false; foreach (Key key in keys) { result |= Keyboard.IsKeyDown(key); } if (result) { return true; } return false; } } }