private void OnPreviewKey(KeyEventArgs e) { // As KeyDown and KeyUp bubble, it appears they're being handled before they get a chance to // trigger the appropriate WM_ messages handled by our SourceHook, so we have to handle these extra keys here. // Hooking the Tab key like this makes the tab focusing in essence work like // KeyboardNavigation.TabNavigation="Cycle"; you will never be able to Tab out of the web browser control. // We also add the condition to allow ctrl+a to work when the web browser control is put inside listbox. if (e.Key == Key.Tab || e.Key == Key.Home || e.Key == Key.End || e.Key == Key.Up || e.Key == Key.Down || e.Key == Key.Left || e.Key == Key.Right || (e.Key == Key.A && Keyboard.Modifiers == ModifierKeys.Control)) { var modifiers = e.GetModifiers(); var message = (int)(e.IsDown ? WM.KEYDOWN : WM.KEYUP); var virtualKey = KeyInterop.VirtualKeyFromKey(e.Key); e.Handled = managedCefBrowserAdapter.SendKeyEvent(message, virtualKey, (int)modifiers); } }
// ****************************************************************** public bool Register() { int virtualKeyCode = KeyInterop.VirtualKeyFromKey(Key); Id = virtualKeyCode + ((int)KeyModifiers * 0x10000); bool result = RegisterHotKey(IntPtr.Zero, Id, (UInt32)KeyModifiers, (UInt32)virtualKeyCode); if (_dictHotKeyToCalBackProc == null) { _dictHotKeyToCalBackProc = new Dictionary <int, HotKey>(); ComponentDispatcher.ThreadFilterMessage += new ThreadMessageEventHandler(ComponentDispatcherThreadFilterMessage); } _dictHotKeyToCalBackProc.Add(Id, this); Debug.Print(result.ToString() + ", " + Id + ", " + virtualKeyCode); return(result); }
public static async void ForceFindDUIAndHide(bool minimizeDUI = true) { await Task.Run(() => { int tries = 0; while (GetAllInfos() == false && tries++ < MAX_TRIES) { //Sometimes the volume flyout isn't created yet, so we need to send some a key stroke. keybd_event((byte)KeyInterop.VirtualKeyFromKey(Key.VolumeUp), 0, 0, 0); keybd_event((byte)KeyInterop.VirtualKeyFromKey(Key.VolumeDown), 0, 0, 0); FindDUIAndHide(minimizeDUI); Thread.Sleep(500); } }); }
// ****************************************************************** public bool Register() { var virtualKeyCode = KeyInterop.VirtualKeyFromKey(Key); Id = virtualKeyCode + ((int)KeyModifiers * 0x10000); var result = NativeMethods.RegisterHotKey(IntPtr.Zero, Id, (UInt32)KeyModifiers, (UInt32)virtualKeyCode); if (_dictHotKeyToCalBackProc == null) { _dictHotKeyToCalBackProc = new Dictionary <int, HotKey>(); ComponentDispatcher.ThreadFilterMessage += ComponentDispatcherThreadFilterMessage; } _dictHotKeyToCalBackProc.Add(Id, this); Debug.Print(result + ", " + Id + ", " + virtualKeyCode); return(result); }
private bool SaveAction() { try { var regex = new Regex("finger_[0-9]+_start_[XY]?|finger_[0-9]+_end_[XY]?|finger_[0-9]+_ID"); var replaced = regex.Replace(ConditionTextBox.Text, "10"); DataTable dataTable = new DataTable(); dataTable.Compute(replaced, null); } catch (Exception exception) { return(ShowErrorMessage(LocalizationProvider.Instance.GetTextValue("ActionDialog.Messages.ConditionError"), exception.Message)); } // Move command to existing action var sameAction = _sourceApplication.Actions.Find(a => a.GestureName == CurrentGesture?.Name); if (sameAction != null) { NewAction = sameAction; } else { _sourceApplication.AddAction(NewAction); } // Store new values NewAction.Condition = string.IsNullOrWhiteSpace(ConditionTextBox.Text) ? null : ConditionTextBox.Text; NewAction.ActivateWindow = ActivateWindowCheckBox.IsChecked; NewAction.GestureName = CurrentGesture?.Name ?? string.Empty; NewAction.Name = ActionNameTextBox.Text.Trim(); NewAction.MouseHotkey = (MouseActions?)MouseActionComboBox.SelectedValue ?? MouseActions.None; NewAction.Hotkey = HotKeyTextBox.HotKey != null ? new Hotkey() { KeyCode = KeyInterop.VirtualKeyFromKey(HotKeyTextBox.HotKey.Key), ModifierKeys = (int)HotKeyTextBox.HotKey.ModifierKeys } : null; // Save entire list of applications ApplicationManager.Instance.SaveApplications(); return(true); }
/// <summary> /// Get the name of the key by using Win32 API. This will resolve weird keys like D1, OEM5, etc. /// </summary> /// <param name="this"></param> /// <returns></returns> public static string GetName(this Key @this) { var vk = (uint)KeyInterop.VirtualKeyFromKey(@this); var hKl = User32.GetKeyboardLayout(0); var sc = (int)User32.MapVirtualKeyEx(vk, User32.MAPVK.MAPVK_VK_TO_VSC_EX, hKl); // seems like the MapVirtualKeyEx is already fixed to include extended bit // (http://web.archive.org/web/20101022020556/http://blogs.msdn.com/b/michkap/archive/2006/08/29/729476.aspx) // but weirdly it doesn't // so we need to add in the extended bit manually // ref: http://www.setnode.com/blog/mapvirtualkey-getkeynametext-and-a-story-of-how-to/ // https://stackoverflow.com/questions/38100667/windows-virtual-key-codes switch ((VK)vk) { case VK.LEFT: case VK.UP: case VK.RIGHT: case VK.DOWN: case VK.RCONTROL: case VK.RMENU: case VK.LWIN: case VK.RWIN: case VK.APPS: case VK.PRIOR: case VK.NEXT: case VK.END: case VK.HOME: case VK.INSERT: case VK.DELETE: case VK.DIVIDE: case VK.NUMLOCK: sc |= (int)KF.EXTENDED; break; } var result = new StringBuilder(255); User32.GetKeyNameText(sc << 16, result, result.Capacity); var str = result.ToString(); return(string.IsNullOrEmpty(str) ? @this.ToString() : str); }
/// <summary> /// 入力されたキーの文字を返し、文字でない場合は null を返します。 /// </summary> public static char?GetCharFromKey(Key p_key) { char?l_ch = null; var l_virtualKey = KeyInterop.VirtualKeyFromKey(p_key); var l_keyboardState = new byte[256]; Interop.GetKeyboardState(l_keyboardState); var l_scanCode = Interop.MapVirtualKey( (uint)l_virtualKey, MapType.MAPVK_VK_TO_VSC); var l_stringBuilder = new StringBuilder(2); var l_result = Interop.ToUnicode( (uint)l_virtualKey, l_scanCode, l_keyboardState, l_stringBuilder, l_stringBuilder.Capacity, 0); switch (l_result) { case -1: break; case 0: break; case 1: l_ch = l_stringBuilder[0]; break; default: l_ch = l_stringBuilder[0]; break; } return(l_ch); }
public async void OnPreviewKeyDown(object sender, KeyEventArgs e) { e.Handled = true; Key key = e.ImeProcessedKey == Key.None ? e.Key : e.ImeProcessedKey; int vkCode = KeyInterop.VirtualKeyFromKey(key); int result = _profileSwitchKeyTableManager.SetSwitchKeyByIndex(_fromIdx, _toIdx, vkCode); //Use WindowManager rather than directly access to view CustomMessageDialog customMessageDialog; switch (result) { case -2: customMessageDialog = new CustomMessageDialog($"{key} is already reserved for activation key."); customMessageDialog.ShowDialog(); break; case -1: customMessageDialog = new CustomMessageDialog($"{key} is already used for other switch key."); customMessageDialog.ShowDialog(); break; case 0: customMessageDialog = new CustomMessageDialog($"{key} is already registerd as a hotkey of this profile"); customMessageDialog.ShowDialog(); break; default: await _profileSwitchKeyTableManager.SaveTableAsync(); NotifyOfPropertyChange(() => SwitchKey); break; } }
public Configuration GetConfiguration(int pid) { var reload = 0x74; var recompile = 0x77; var antiAfk = false; var console = false; var towerRange = false; var extendedZoom = false; var menuToggle = 0x78; var menuPress = 0x10; try { reload = KeyInterop.VirtualKeyFromKey(Config.Instance.Hotkeys.SelectedHotkeys.First(h => h.Name == "Reload").Hotkey); recompile = KeyInterop.VirtualKeyFromKey(Config.Instance.Hotkeys.SelectedHotkeys.First(h => h.Name == "CompileAndReload").Hotkey); antiAfk = Config.Instance.Settings.GameSettings.First(s => s.Name == "Anti-AFK").SelectedValue == "True"; console = Config.Instance.Settings.GameSettings.First(s => s.Name == "Debug Console").SelectedValue == "True"; towerRange = Config.Instance.Settings.GameSettings.First(s => s.Name == "Display Enemy Tower Range").SelectedValue == "True"; extendedZoom = Config.Instance.Settings.GameSettings.First(s => s.Name == "Extended Zoom").SelectedValue == "True"; menuToggle = KeyInterop.VirtualKeyFromKey(Config.Instance.Hotkeys.SelectedHotkeys.First(h => h.Name == "ShowMenuToggle").Hotkey); menuPress = KeyInterop.VirtualKeyFromKey(Config.Instance.Hotkeys.SelectedHotkeys.First(h => h.Name == "ShowMenuPress").Hotkey); } catch { // ignored } return(new Configuration { DataDirectory = Directories.AppDataDirectory, LeagueSharpDllPath = PathRandomizer.LeagueSharpDllPath, LibrariesDirectory = Directories.CoreDirectory, ReloadKey = reload, ReloadAndRecompileKey = recompile, MenuToggleKey = menuToggle, MenuKey = menuPress, UnloadKey = 0x75, AntiAfk = antiAfk, Console = console, TowerRange = towerRange, ExtendedZoom = false, Permissions = null }); }
/// <summary> /// The start. /// </summary> /// <param name="lengthBarcode"> /// The length string of barcode. /// </param> public void Start(byte lengthBarcode) { if (Application.Current == null || Application.Current.MainWindow == null) { LogManager.Log.Debug("Application.Current == null || Application.Current.MainWindow == null"); return; } this.Stop(); string barcode = string.Empty; var keyDown = Observable.FromEventPattern <KeyEventHandler, KeyEventArgs>( h => Application.Current.MainWindow.KeyDown += h, h => Application.Current.MainWindow.KeyDown -= h).Select(args => args.EventArgs); var keyTilda = keyDown.Where( args => (Keyboard.Modifiers & ModifierKeys.Shift) == ModifierKeys.Shift && args.Key == Key.OemTilde); var keyPipe = keyTilda.Select(_ => keyDown.Where(args => args.Key == Key.OemPipe)).Concat(); _disposable = keyPipe .Do(_ => barcode = string.Empty) .Do(args => args.Handled = true) .Select(x => keyDown.Do(args => args.Handled = true) .TakeUntil(keyDown.TimeInterval().Where(args => args.Value.Key == Key.Enter || args.Interval.TotalMilliseconds > 50)) .Select(args => ((char)KeyInterop.VirtualKeyFromKey(args.Key)).ToString(CultureInfo.InvariantCulture)) .Do(symbol => barcode += symbol) .Finally(() => { if (barcode.Length == lengthBarcode) { this.OnEnteredBarcode(barcode); } barcode = string.Empty; })) .Concat() .Subscribe(); }
private void OnKeyUpHandler(object sender, KeyEventArgs e) { uint scancode = User32.MapVirtualKeyA((uint)KeyInterop.VirtualKeyFromKey(e.Key), User32.MapVirtualKeyMapTypes.MAPVK_VK_TO_VSC_EX); switch (scancode) { case (uint)ScanCodes.W: m_keyWasPressed[1] = false; break; case (uint)ScanCodes.S: m_keyWasPressed[4] = false; break; case (uint)ScanCodes.A: m_keyWasPressed[3] = false; break; case (uint)ScanCodes.D: m_keyWasPressed[5] = false; break; case (uint)ScanCodes.E: m_keyWasPressed[2] = false; break; case (uint)ScanCodes.Q: m_keyWasPressed[0] = false; break; } }
/// <summary> /// Converts Key to Char (considering keyboard layout defined in the given culture) /// </summary> /// <param name="key">Key</param> /// <param name="cultureInfo">Culture</param> /// <returns>Char</returns> public static char?KeyToChar(Key key, CultureInfo cultureInfo) { // Get layouts existed in the system if (existingLayouts == null) { int keyboardsCount = NativeMethods.GetKeyboardLayoutList(0, null); existingLayouts = new IntPtr[keyboardsCount]; NativeMethods.GetKeyboardLayoutList(keyboardsCount, existingLayouts); } int virtualKey = KeyInterop.VirtualKeyFromKey(key); // Try to find keyboard layout in cache IntPtr keyboardlayout; if (!keyboardLayoutHandlers.TryGetValue(cultureInfo.LCID, out keyboardlayout)) { keyboardlayout = NativeMethods.LoadKeyboardLayout(cultureInfo.LCID.ToString("x8", CultureInfo.InvariantCulture), 0x00000080); keyboardLayoutHandlers.Add(cultureInfo.LCID, keyboardlayout); } // Get keyboard status bool bKeyStateStatus = NativeMethods.GetKeyboardState(keyboardState); if (!bKeyStateStatus) { return(null); } uint scanCode = NativeMethods.MapVirtualKeyEx((uint)virtualKey, 2, keyboardlayout); StringBuilder result = new StringBuilder(10); int count = NativeMethods.ToUnicodeEx((uint)virtualKey, scanCode, keyboardState, result, 10, 0, keyboardlayout); if (!existingLayouts.Contains(keyboardlayout)) { // We must unload the layout to be sure // that previously non-existed layout remains in the system NativeMethods.UnloadKeyboardLayout(keyboardlayout); keyboardLayoutHandlers.Remove(cultureInfo.LCID); } return((result.Length >= 1 && count >= 1) ? new char?(result[0]) : null); }
private void FunctionsView_KeyDown(object sender, KeyEventArgs e) { char c = (char)KeyInterop.VirtualKeyFromKey(e.Key); if (c == '\b') { if (searchBuffer.Length != 0) { searchBuffer = searchBuffer.Substring(0, searchBuffer.Length - 1); } } else if (Char.IsLetterOrDigit(c)) { searchBuffer += c; } SearchBufferView.Text = searchBuffer; FunctionViewSearchNext(); }
public static KeyboardEvent Convert(this KeyEventArgs e) { return(new KeyboardEvent { KeyStates = e.KeyStates, VkKey = e.Key == Key.System ? KeyInterop.VirtualKeyFromKey(e.SystemKey) : e.Key == Key.ImeProcessed ? KeyInterop.VirtualKeyFromKey(e.ImeProcessedKey) : e.Key == Key.DeadCharProcessed ? KeyInterop.VirtualKeyFromKey(e.DeadCharProcessedKey) : KeyInterop.VirtualKeyFromKey(e.Key), IsSystemKey = e.Key == Key.System, VkSystemKey = KeyInterop.VirtualKeyFromKey(e.SystemKey), IsRepeat = e.IsRepeat, IsDown = e.IsDown, IsUp = e.IsUp, IsToggled = e.IsToggled, }); }
public static HotKey GetInstance(Key key, KeyModifier keyModifiers) { HotKey hk; int virtualKeyCode = KeyInterop.VirtualKeyFromKey(key); int id = virtualKeyCode + ((int)keyModifiers * 0x10000); if (dictHotKeys == null) { dictHotKeys = new Dictionary <int, HotKey>(); } if (!dictHotKeys.TryGetValue(id, out hk)) { hk = new HotKey(key, keyModifiers, id, virtualKeyCode); dictHotKeys.Add(id, hk); } return(hk); }
/// <summary> /// KeyPress /// </summary> /// <param name="key">key name</param> /// <param name="pressedMillionSeconds">pressed time</param> /// <returns></returns> public static async Task KeyPress(Key key, uint pressedMillionSeconds = KeyPressedTime) { if (WindowsApi.Delay.HasValue) { Thread.Sleep(WindowsApi.Delay.Value); } var keyByte = (byte)KeyInterop.VirtualKeyFromKey(key); keybd_event(keyByte, 0, KeyDownFlag, IntPtr.Zero); if (pressedMillionSeconds != 0u) { await Task.Delay(TimeSpan.FromMilliseconds(pressedMillionSeconds)); } keybd_event(keyByte, 0, KeyUpFlag, IntPtr.Zero); WindowsApi.WriteLog($"{nameof(KeyPress)} {key} {nameof(KeyPressedTime)}:{pressedMillionSeconds}"); }
/// <summary> /// RegisterHotKey method registers a hotkey with a system. /// </summary> /// <param name="modKeys">Specify a combination of modifier keys.</param> /// <param name="key">Specify a typical key.</param> /// <param name="action">Specify an action that is executed when the hotkey is pressed.</param> /// <returns>true if the hotkey is registered successfully; otherwise, false</returns> public bool RegisterHotKey(ModifierKeys modKeys, Key key, Action action) { try { int id = GetNextId(); _keyPairIndex.Add(new Pair <int, int>((int)modKeys, (int)key), id); _idIndex.Add(id, action); int result = 0; _window.Dispatcher.Invoke((Action)(() => { result = RegisterHotKey(_windowHandle, id, (int)modKeys, KeyInterop.VirtualKeyFromKey(key)); }), null); return(result != 0); } catch (InvalidOperationException e) { Debug.WriteLine(e.ToString()); return(false); } }
/// <summary> /// When the window captures a key press event, this handler records the key that was pressed /// and updates the view model. /// </summary> private void Window_KeyDown(object sender, KeyEventArgs e) { // Convert key to System.Windows.Forms because that is the type // that the application uses. var pressedKey = e.Key == Key.System ? e.SystemKey : e.Key; var convertedFormsKey = (Forms.Keys)KeyInterop.VirtualKeyFromKey(pressedKey); // Consolidate all variations of the same key (LShift == RShift) var consolidatedKey = convertedFormsKey.Consolidate(); // Don't allow duplicate keys to be tracked. if (!_pressedKeys.Contains(consolidatedKey)) { _pressedKeys.Add(consolidatedKey); _model.KeyCombinationString = string.Join("+", _pressedKeys.Select(k => k.GetKeyDescription())); } e.Handled = true; }
public void OnPreviewKeyDown(KeyEventArgs e) { if (e.Key == Key.Enter) { return; } if (e.Key == Key.Tab) { return; } Hotkey.Modifiers = System.Windows.Forms.Keys.None; Hotkey.Key = System.Windows.Forms.Keys.None; if (Keyboard.IsKeyDown(Key.LeftCtrl) || Keyboard.IsKeyDown(Key.RightCtrl)) { Hotkey.Modifiers = System.Windows.Forms.Keys.Control; } if (Keyboard.IsKeyDown(Key.LeftShift) || Keyboard.IsKeyDown(Key.RightShift)) { Hotkey.Modifiers |= System.Windows.Forms.Keys.Shift; } if (Keyboard.IsKeyDown(Key.LeftAlt) || Keyboard.IsKeyDown(Key.RightAlt)) { Hotkey.Modifiers |= System.Windows.Forms.Keys.Alt; } if (e.Key == Key.LeftShift || e.Key == Key.RightShift || e.Key == Key.LeftAlt || e.Key == Key.RightAlt || e.Key == Key.LeftCtrl || e.Key == Key.RightCtrl || e.Key == Key.CapsLock || e.Key == Key.LWin || e.Key == Key.RWin) { // Ignore all types of modifiers } else { Hotkey.Key = (System.Windows.Forms.Keys)KeyInterop.VirtualKeyFromKey(e.Key); } RaisePropertyChanged(nameof(HotkeyText)); }
private void ApplyHotKey(object sender, RoutedEventArgs e) { bool containsFunKey = _funcKeys.Contains(Key.LeftAlt) | _funcKeys.Contains(Key.LeftCtrl) | _funcKeys.Contains(Key.LeftShift) | _funcKeys.Contains(Key.CapsLock); if (!containsFunKey | _key == Key.None) { HandyControl.Controls.Growl.Error("必须为 功能键 + 数字/字母", "SettingsGrowl"); } else { //注册热键 if (_key != Key.None & IsProperFuncKey(_funcKeys)) { uint fsModifiers = (uint)Modifiers.None; foreach (Key key in _funcKeys) { if (key == Key.LeftCtrl) fsModifiers = fsModifiers | (uint)Modifiers.Control; if (key == Key.LeftAlt) fsModifiers = fsModifiers | (uint)Modifiers.Alt; if (key == Key.LeftShift) fsModifiers = fsModifiers | (uint)Modifiers.Shift; } VK = (uint)KeyInterop.VirtualKeyFromKey(_key); UnregisterHotKey(_windowHandle, HOTKEY_ID);//取消之前的热键 bool success = RegisterHotKey(_windowHandle, HOTKEY_ID, fsModifiers, VK); if (!success) { MessageBox.Show("热键冲突!", "热键冲突"); } { //保存设置 Properties.Settings.Default.HotKey_Modifiers = fsModifiers; Properties.Settings.Default.HotKey_VK = VK; Properties.Settings.Default.HotKey_Enable = true; Properties.Settings.Default.HotKey_String = hotkeyTextBox.Text; Properties.Settings.Default.Save(); HandyControl.Controls.Growl.Success("设置热键成功", "SettingsGrowl"); } } } }
/// <summary> /// Registers the hotkey. /// </summary> /// <returns>Whether the registration is successful.</returns> public bool Register() { var virtualKeyCode = KeyInterop.VirtualKeyFromKey(VirtualKey); KeyId = virtualKeyCode + ((int)ModifierKeyCombo * 0x10000); ComponentDispatcher.ThreadFilterMessage += (ref MSG msg, ref bool handled) => { if (msg.message == WM_HOTKEY && !handled) { _keyAction.Invoke(); handled = true; } }; // key params to pass: hotkey combo and its unique keyId return(RegisterHotKey(IntPtr.Zero, KeyId, (uint)ModifierKeyCombo, (uint)virtualKeyCode)); }
private void Hook_KeyboardPressed(object sender, GlobalKeyboardHookEventArgs e) { var virtualCode = e.KeyboardData.VirtualCode; // ESC pressed if (virtualCode == KeyInterop.VirtualKeyFromKey(Key.Escape)) { _currentlyPressedKeys.Clear(); _appStateHandler.HideColorPicker(); PowerToysTelemetry.Log.WriteEvent(new ColorPickerCancelledEvent()); } var name = Helper.GetKeyName((uint)virtualCode); // we got modifier with additional info such as "Ctrl (left)" - get rid of parenthesess if (name.IndexOf("(", StringComparison.OrdinalIgnoreCase) > 0 && name.Length > 1) { name = name.Substring(0, name.IndexOf("(", StringComparison.OrdinalIgnoreCase)).Trim(); } if (e.KeyboardState == GlobalKeyboardHook.KeyboardState.KeyDown || e.KeyboardState == GlobalKeyboardHook.KeyboardState.SysKeyDown) { if (!_currentlyPressedKeys.Contains(name)) { _currentlyPressedKeys.Add(name); } } else if (e.KeyboardState == GlobalKeyboardHook.KeyboardState.KeyUp || e.KeyboardState == GlobalKeyboardHook.KeyboardState.SysKeyUp) { if (_currentlyPressedKeys.Contains(name)) { _currentlyPressedKeys.Remove(name); } } _currentlyPressedKeys.Sort(); if (ArraysAreSame(_currentlyPressedKeys, _activationKeys)) { _appStateHandler.ShowColorPicker(); _currentlyPressedKeys.Clear(); } }
private void Window_PreviewKeyDown(object sender, KeyEventArgs e) { if (e.Key == Key.Enter) { return; } if (e.Key == Key.Tab) { return; } Hotkey.Modifiers = System.Windows.Forms.Keys.None; Hotkey.Key = System.Windows.Forms.Keys.None; if (Keyboard.IsKeyDown(Key.LeftCtrl) || Keyboard.IsKeyDown(Key.RightCtrl)) { Hotkey.Modifiers = System.Windows.Forms.Keys.Control; } if (Keyboard.IsKeyDown(Key.LeftShift) || Keyboard.IsKeyDown(Key.RightShift)) { Hotkey.Modifiers |= System.Windows.Forms.Keys.Shift; } if (Keyboard.IsKeyDown(Key.LeftAlt) || Keyboard.IsKeyDown(Key.RightAlt)) { Hotkey.Modifiers |= System.Windows.Forms.Keys.Alt; } if (e.Key == Key.LeftShift || e.Key == Key.RightShift || e.Key == Key.LeftAlt || e.Key == Key.RightAlt || e.Key == Key.LeftCtrl || e.Key == Key.RightCtrl || e.Key == Key.CapsLock || e.Key == Key.LWin || e.Key == Key.RWin) { // Ignore all types of modifiers } else { Hotkey.Key = (System.Windows.Forms.Keys)KeyInterop.VirtualKeyFromKey(e.Key); } UpdateText(); }
/// <summary> /// WindowProc callback interceptor. Handles Windows messages intended for the source hWnd, and passes them to the /// contained browser as needed. /// </summary> /// <param name="hWnd">The source handle.</param> /// <param name="message">The message.</param> /// <param name="wParam">Additional message info.</param> /// <param name="lParam">Even more message info.</param> /// <param name="handled">if set to <c>true</c>, the event has already been handled by someone else.</param> /// <returns>IntPtr.</returns> protected virtual IntPtr SourceHook(IntPtr hWnd, int message, IntPtr wParam, IntPtr lParam, ref bool handled) { if (handled) { return(IntPtr.Zero); } switch ((WM)message) { case WM.SYSCHAR: case WM.SYSKEYDOWN: case WM.SYSKEYUP: case WM.KEYDOWN: case WM.KEYUP: case WM.CHAR: case WM.IME_CHAR: { if (!owner.IsKeyboardFocused) { break; } if (message == (int)WM.SYSKEYDOWN && wParam.ToInt32() == KeyInterop.VirtualKeyFromKey(Key.F4)) { // We don't want CEF to receive this event (and mark it as handled), since that makes it impossible to // shut down a CefSharp-based app by pressing Alt-F4, which is kind of bad. return(IntPtr.Zero); } var browser = owner.BrowserCore; if (browser != null) { browser.GetHost().SendKeyEvent(message, wParam.CastToInt32(), lParam.CastToInt32()); handled = true; } break; } } return(IntPtr.Zero); }
private void Window_OnKeyUp(object sender, KeyEventArgs keyEventArgs) { if (IsWaitingForKeyInput) { if (keyEventArgs.Key == Key.Escape) { } else if (keyEventArgs.Key == Key.Back) { if (SelectedConfig.KeyBinding != null) { UnregisterHotKey(_windowHandle, KeyInterop.VirtualKeyFromKey(SelectedConfig.KeyBinding.Key)); } SelectedConfig.KeyBinding = null; _configService.SaveConfig(SelectedConfig); } else { if (SelectedConfig.KeyBinding != null) { UnregisterHotKey(_windowHandle, KeyInterop.VirtualKeyFromKey(SelectedConfig.KeyBinding.Key)); } SelectedConfig.KeyBinding = new KeyData(keyEventArgs.Key == Key.System ? keyEventArgs.SystemKey : keyEventArgs.Key, Keyboard.IsKeyDown(Key.LeftShift), Keyboard.IsKeyDown(Key.LeftAlt), Keyboard.IsKeyDown(Key.LeftCtrl)); _configService.SaveConfig(SelectedConfig); uint mask = SelectedConfig.KeyBinding.Alt ? (uint)0x0001 : 0; mask = mask | (SelectedConfig.KeyBinding.Control ? (uint)0x0002 : 0); mask = mask | (SelectedConfig.KeyBinding.Shift ? (uint)0x0004 : 0); mask = mask | 0x4000; int virtualKeyCode = KeyInterop.VirtualKeyFromKey(SelectedConfig.KeyBinding.Key); if (!RegisterHotKey(_windowHandle, virtualKeyCode, mask, (uint)virtualKeyCode)) { MessageBox.Show("Cannot bind key " + SelectedConfig.KeyBinding); } } IsWaitingForKeyInput = false; } }
// ****************************************************************** public bool Register() { int virtualKeyCode = KeyInterop.VirtualKeyFromKey(Key); Id = virtualKeyCode + ((int)KeyModifiers * 0x10000); bool result = RegisterHotKey(IntPtr.Zero, Id, (uint)KeyModifiers, (uint)virtualKeyCode); if (dictHotKeyToCalBackProc == null) { dictHotKeyToCalBackProc = new Dictionary <int, GlobalHotKey>(); ComponentDispatcher.ThreadFilterMessage += new ThreadMessageEventHandler(ComponentDispatcherThreadFilterMessage); } dictHotKeyToCalBackProc.Add(Id, this); Debug.Print($"{result}, {Id}, {virtualKeyCode}"); return(result); }
public static string CharsOfKey(Key key) { uint vk = (uint)KeyInterop.VirtualKeyFromKey(key); byte[] keyState = new byte[256]; Win32.GetKeyboardState(keyState); uint scancode = Win32.MapVirtualKey(vk, (uint)Win32.MapType.MAPVK_VK_TO_VSC); char[] buffer = new char[10]; int count = Win32.ToUnicode(vk, scancode, keyState, buffer, buffer.Length, 0); if (count < 0) { count = 0; } char[] result = new char[count]; Array.Copy(buffer, result, count); return(new string(result)); }
public bool Register(ModifierKeys modifierKey, Key key) { int modkey = (int)modifierKey; int virtualKey = KeyInterop.VirtualKeyFromKey(key); int hotkeyId = 0x0000; while (hotkeyId < MAX_HOTKEY_ID) { var success = RegisterHotKey(windowHandle, hotkeyId, modkey, virtualKey) != 0; if (success) { this.hotkeyId = hotkeyId; return(true); } hotkeyId++; } return(false); }
private void TextBoxPreviewKeyDown(object sender, KeyEventArgs e) { try { var textBox = ((TextBox)sender); if (textBox.Tag == null) { textBox.Tag = KeyPressLength.ThirtyTwoMilliSec; } var keyPressed = KeyInterop.VirtualKeyFromKey(e.SystemKey == Key.F10 ? Key.F10 : e.Key); e.Handled = true; var hashSetOfKeysPressed = new HashSet <string>(); hashSetOfKeysPressed.Add(Enum.GetName(typeof(VirtualKeyCode), keyPressed)); var modifiers = CommonVK.GetPressedVirtualKeyCodesThatAreModifiers(); foreach (var virtualKeyCode in modifiers) { hashSetOfKeysPressed.Add(Enum.GetName(typeof(VirtualKeyCode), virtualKeyCode)); } var result = ""; foreach (var str in hashSetOfKeysPressed) { if (!string.IsNullOrEmpty(result)) { result = str + " + " + result; } else { result = str + " " + result; } } result = Common.RemoveRControl(result); textBox.Text = result; SetIsDirty(); SetFormState(); } catch (Exception ex) { MessageBox.Show(ex.Message); } }
public static string ConvertKeyToUnicode(System.Windows.Input.Key key, IntPtr inputHandle) { if (inputHandle.ToInt32() == 0) { inputHandle = InputLanguage.CurrentInputLanguage.Handle; } StringBuilder result = new StringBuilder(2); Keys[] keyStates = new Keys[256]; if (GetKeyboardState(keyStates)) { ToUnicodeEx((uint)KeyInterop.VirtualKeyFromKey(key), 0, keyStates, result, result.Capacity, 0, inputHandle); if (result.Length > 0) { return(result[0].ToString()); } } return(""); }