/// <summary> /// 注册热键 - 成功后,会设置 HotKeyID /// </summary> /// <param name="item">The item.</param> /// <exception cref="ArgumentNullException"> /// item /// or /// HotKey - 热键不能为空! /// </exception> /// <exception cref="InvalidOperationException"> /// 功能键不能为空! /// or /// 快捷键不能为空! /// </exception> public void RegKey(HotKeyItem item) { if (item is null) { throw new ArgumentNullException(nameof(item)); } if (string.IsNullOrWhiteSpace(item.HotKey)) { throw new ArgumentNullException(nameof(item.HotKey), "热键不能为空!"); } // 如果注册过该热键,ID不为0。卸载热键会将ID置零。 if (item.HotKeyID != 0) { return; } int id = Interlocked.Increment(ref _RegMaxID); var keys = item.HotKey.Split('+'); Keys keyCode = Keys.None; AppHotKey.KeyModifiers keyModifiers = AppHotKey.KeyModifiers.None; foreach (var key in keys) { switch (key.ToLower()) { case "ctrl": keyModifiers |= AppHotKey.KeyModifiers.Ctrl; break; case "shift": keyModifiers |= AppHotKey.KeyModifiers.Shift; break; case "alt": keyModifiers |= AppHotKey.KeyModifiers.Alt; break; case "win": keyModifiers |= AppHotKey.KeyModifiers.WindowsKey; break; default: keyCode = (Keys)Enum.Parse(typeof(Keys), key); break; } } if (keyModifiers == AppHotKey.KeyModifiers.None) { throw new InvalidOperationException("功能键不能为空!"); } if (keyCode == Keys.None) { throw new InvalidOperationException("快捷键不能为空!"); } AppHotKey.RegKey(FormHandle, id, keyModifiers, keyCode); item.HotKeyID = id; }
protected override void WndProc(ref Message m) { base.WndProc(ref m); switch (m.Msg) { case WM_HOTKEY: switch (m.WParam.ToInt32()) { case KEY_ID: if (Visible) { Hide(); } else { Show(); } break; } break; case WM_CREATE: try { string hotKeys = DBLinker.GetOneLine(@" select keyValue from config where keyName = 'HotKeys' limit 1; "); if (hotKeys == null) { return; } string[] hotKeyTextArray = hotKeys.Split(';'); AppHotKey.KeyModifiers keyModifiers = AppHotKey.KeyModifiers.None; switch (hotKeyTextArray[0]) { case "Win": keyModifiers = AppHotKey.KeyModifiers.WindowsKey; break; case "Alt": keyModifiers = AppHotKey.KeyModifiers.Alt; break; case "Ctrl": keyModifiers = AppHotKey.KeyModifiers.Ctrl; break; case "Shift": keyModifiers = AppHotKey.KeyModifiers.Shift; break; default: keyModifiers = AppHotKey.KeyModifiers.None; break; } AppHotKey.RegKey(Handle, KEY_ID, keyModifiers, AppHotKey.KeyMap(hotKeyTextArray[1])); } catch (Exception ex) { MessageBox.Show(ex.Message); } break; case WM_DESTROY: AppHotKey.UnRegKey(Handle, KEY_ID); break; } }