Get lowercase with keydown wpf

前端 未结 5 2106
再見小時候
再見小時候 2020-12-20 17:36

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         


        
5条回答
  •  情深已故
    2020-12-20 18:21

    The best way to handle this is by using Window_TextInput event rather than KeyDown.

    But as you said this event does not fire on your application you can rather use a 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 properly print the characters based on whether capslock is turned on or not. The initial value of the Capslock can be retrieved using this link :

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

    I hope this works for you.

提交回复
热议问题