I want to get the keys pressed on the keyboard either with or without caplock:
private void Window_KeyDown(object sender, System.Windows.Input.KeyEventArgs e)
{
e.Key.ToString();
}
When I type "a" or "A" on the keyboard, the result of e.Key is always "A". How can I get 'a' for entering 'a'?
You can't use the KeyDown
event. You'll need to use the TextInput
event. This will print the original letter with it's caption (Uppercase/Lowercase).
private void Window_TextInput(object sender, TextCompositionEventArgs e)
{
Console.WriteLine(e.Text);
}
Now, this will also print the Shift and so on if it's pressed. If you don't want those modifiers just get the last item of the string -treat it as a char array ;)-
You can check in your KeyDown
event whether CAPS lock
is on or off using Control.IsKeyLocked method. Also, you might need to check if user typed in capital using Shift
key which can be identified using Modifiers
enum like this -
private void Window_KeyDown(object sender, KeyEventArgs e)
{
string key = e.Key.ToString();
bool isCapsLockOn = System.Windows.Forms.Control
.IsKeyLocked(System.Windows.Forms.Keys.CapsLock);
bool isShiftKeyPressed = (Keyboard.Modifiers & ModifierKeys.Shift)
== ModifierKeys.Shift;
if (!isCapsLockOn && !isShiftKeyPressed)
{
key = key.ToLower();
}
}
Overriding TextInput/PreviewTextInput (or listening to the events) should work.
protected override void OnPreviewTextInput(TextCompositionEventArgs e)
{
base.OnPreviewTextInput(e);
Console.WriteLine(e.Text);
}
KeyEventArgs class has "Shift" field which indicating whether the SHIFT key was pressed.
Otherwise, because Window_KeyDown method will be called when CAPS_LOCK pressed, you can save a bool value indicating whether the CAPS_LOCK key was pressed.
bool isCapsLockPressed;
private void Window_KeyDown(object sender, System.Windows.Input.KeyEventArgs e) {
if(e.KeyCode == Keys.CapsLock) {
isCapsLockPressed = !isCapsLockPressed;
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With