Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get lowercase with keydown wpf

Tags:

wpf

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'?

like image 886
olidev Avatar asked Sep 25 '12 22:09

olidev


4 Answers

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 ;)-

like image 122
Erre Efe Avatar answered Nov 05 '22 09:11

Erre Efe


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();
   }
}
like image 7
Rohit Vats Avatar answered Nov 05 '22 09:11

Rohit Vats


Overriding TextInput/PreviewTextInput (or listening to the events) should work.

protected override void OnPreviewTextInput(TextCompositionEventArgs e)
{
    base.OnPreviewTextInput(e);
    Console.WriteLine(e.Text);
}
like image 5
Hadi Eskandari Avatar answered Nov 05 '22 09:11

Hadi Eskandari


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;
           }
    }
like image 2
wangxt Avatar answered Nov 05 '22 10:11

wangxt