Get lowercase letters with wpf key

I want the keys to be pressed on the keyboard with or without a hood:

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" to enter "a"?

Thanks in advance.

+6
source share
5 answers

You cannot use the KeyDown . You will need to use the TextInput event. This will print the original letter with the inscription (upper or lower case).

  private void Window_TextInput(object sender, TextCompositionEventArgs e) { Console.WriteLine(e.Text); } 

Now it will also print Shift etc. if it is pressed. If you don't want these modifiers to just get the last element of the string, remove it as a char array;) -

+6
source

You can check your KeyDown event to see if CAPS lock enabled using the Control.IsKeyLocked method. In addition, you may need to check if the user is entered in the capital using the Shift , which can be identified with the 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(); } } 
+5
source

Overloading TextInput / PreviewTextInput (or listening for events) should work.

 protected override void OnPreviewTextInput(TextCompositionEventArgs e) { base.OnPreviewTextInput(e); Console.WriteLine(e.Text); } 
+4
source

The KeyEventArgs class has a "Shift" field that indicates whether the SHIFT key has been pressed.

Otherwise, since the Window_KeyDown method will be called when CAPS_LOCK is pressed, you can save a bool that indicates whether the CAPS_LOCK key has been pressed.

  bool isCapsLockPressed; private void Window_KeyDown(object sender, System.Windows.Input.KeyEventArgs e) { if(e.KeyCode == Keys.CapsLock) { isCapsLockPressed = !isCapsLockPressed; } } 
+2
source

The best way to handle this is to use the Window_TextInput event rather than KeyDown.

But, as you said, this event does not fire in your application, you can use the hack like this:

 bool iscapsLock = false; bool isShift = false; private void Window_KeyDown(object sender, KeyEventArgs e) { if (e.Key == Key.CapsLock) iscapsLock = !iscapsLock; if (e.Key >= Key.A && e.Key <= Key.Z) { bool shift = isShift; if (iscapsLock) shift = !shift; int s = e.Key.ToString()[0]; if (!shift) { s += 32; } Debug.Write((char)s); } } 

This will print the characters correctly, depending on whether the hood is on or not. The initial value of Capslock can be obtained using this link:

http://cboard.cprogramming.com/csharp-programming/105103-how-detect-capslock-csharp.html

Hope this works for you.

0
source

Source: https://habr.com/ru/post/926252/


All Articles