Is there a way to do _ for hotkeys without the Alt key?
In WPF, when you create a shortcut like this:
<Label Content="_My Label"/> Then, when you launch the application and press the Alt key, it will display an underlined “M”.
We have our own custom hotkey called Attached Property, which allows us to use Ctrl as well as Alt .
The problem is that only Alt will show underscores.
Is there a way to show an underscore when pressing the Ctrl key?
NOTE. I DO NOT want to send the software Alt KeyPress in the background when pressing Ctrl . It just confuses my quick access system.
Ok! I have a solution to show _ for hotkeys without pressing Alt , but Ctrl is pressed.
Here's how to do it:
Small code for dynamically pressing a KeyBoard key:
//<summary> //Function to Perform a Keyboard KeyPress. //</summary> void PressKey(Key KeyboardKey) { KeyEventArgs args = new KeyEventArgs(Keyboard.PrimaryDevice, Keyboard.PrimaryDevice.ActiveSource, 0, Key.LeftAlt); args.RoutedEvent = Keyboard.KeyDownEvent; InputManager.Current.ProcessInput(args); } Code for adding and removing HotKeyChar :
//<summary> //Function to Append a HotKeyChar to a Content of a Control. //</summary> void AppendHotKeyChar(ContentControl Ctrl, int KeyIndex) { if (Ctrl.Content.ToString().Substring(KeyIndex, 1) != "_") { Ctrl.Content = "_" + Ctrl.Content; } } //<summary> //Function to Remove a HotKeyChar to a Content of a Control. //</summary> void RemoveHotKeyChar(ContentControl Ctrl, int KeyIndex) { if (Ctrl.Content.ToString().Substring(KeyIndex, 1) == "_") { Ctrl.Content = Ctrl.Content.ToString().Remove(KeyIndex, 1); } } XAML Code for Button Bt1 :
<Button x:Name="Bt1" Content="Button" HorizontalAlignment="Left" Margin="169,97,0,0" VerticalAlignment="Top" Width="75"/> Code for Window.Loaded MainWindow events (e.g. MainWindow1_Loaded ):
PressKey(Key.LeftAlt); Code for Window.KeyDown MainWindow event (for example, MainWindow1_KeyDown ):
if (e.Key == Key.LeftCtrl) { AppendHotKey(Bt1, 0); } Code for Window.KeyUp MainWindow event (for example, MainWindow1_KeyUp ):
if (e.Key == Key.LeftCtrl) { RemoveHotKey(Bt1, 0); } Now, when you start the application, Alt will be pressed once dynamically.
And now every time you press Ctrl , your Control.Content will be added with _ , and so the HotKey will appear underlined! But one point is that you should create a Control.Content without HotKeyChar '_' , but keep the Index where your _ will be added.
But keep in mind that if Alt is pressed again in your application, the code will no longer work. So you have to press the Alt button again to make the code work!
Best way to add and remove HotKeyChar :
- Create an instance of
List<KeyValuePair<int, Control>>to storeIndexHotKeyCharandControl. - And now in the
KeyDownjust go throughKeyValuePair<...>toList<...>.. adding_. - In the
KeyValuePair<...>event, again just go throughKeyValuePair<...>toList<...>.. removing_.
Hope this helps!