Reputation: 82361
In WPF when you make a label like this:
<Label Content="_My Label"/>
Then when you run the app and press the Alt key it will show the "M" underlined.
We have our own custom hotkey Attached Property that allows us to use Ctrl as well as Alt.
Problem is that only Alt will show the underscores.
Is there a way to show the underscore when the Ctrl key is pressed?
NOTE: I do NOT want to send a programmatic Alt KeyPress in the background when Ctrl is pressed. That will just confuse my shortcut system.
Upvotes: 7
Views: 1881
Reputation: 2163
Ok! I have got a solution to show the _
for hot-keys without Alt pressed but Ctrl pressed.
Small Code to Press a KeyBoard Key dynamically :
//<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 to Append and Remove 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
event of the MainWindow
(e.g. MainWindow1_Loaded
) :
PressKey(Key.LeftAlt);
Code for Window.KeyDown
event of the MainWindow
(e.g. MainWindow1_KeyDown
) :
if (e.Key == Key.LeftCtrl)
{
AppendHotKey(Bt1, 0);
}
Code for Window.KeyUp
event of the MainWindow
(e.g. MainWindow1_KeyUp
) :
if (e.Key == Key.LeftCtrl)
{
RemoveHotKey(Bt1, 0);
}
Now, When you start your app the Alt will be pressed once dynamically.
And now every-time you press Ctrl, your Control.Content
will be Appended with a _
and so the HotKey
will appear underlined!
But one remark is that you should create Control.Content
without HotKeyChar '_'
but keep an Index
of where your _
will be appended.
But keep in mind that if Alt is pressed again in your app, The code will not work anymore. So, you have to press the Alt again to make the code work!
Best way to appending and removing a HotKeyChar
:
List<KeyValuePair<int, Control>>
to store the Index
of the HotKeyChar
and the Control
.KeyDown
event just loop through the KeyValuePair<...>
in the List<...>
..appending the _
.KeyUp
event again just loop through the KeyValuePair<...>
in the List<...>
..removing the _
.Hope it Helped!
Upvotes: 1