user348173
user348173

Reputation: 9278

Determining which key is pressed

This function has many applications. I have a TextBox control. How to display keys that the user pressed. For example pressed CTRL and z in the TextBox control should appear "Ctrl + Z"? It's WPF application. Thanks.

Now i'm trying like this:

  private void txtHotKey_PreviewKeyUp(object sender, KeyEventArgs e)
    {            
        txtHotKey.Text += e.Key.ToString();
        txtHotKey.Text += "+";
        e.Handled = true;
    }

Now if I pressed Ctrl and Z in the textbox appear "Ctrl+Z+". Then press Ctrl and A. Will be "Ctrl+Z+Ctrl+A+". It's wrong.

Upvotes: 0

Views: 304

Answers (2)

Dennis G
Dennis G

Reputation: 21778

Take a look at the following post with example code: Capture key press events with WPF

Does it help you? You can either attach yourself to the grid (or your textbox) with the KeyDown event handler or you could use a Window_KeyDown method.

Upvotes: 0

Jens
Jens

Reputation: 25563

Have you looked at the KeyEventArgs you get passed to the KeyDown event handler of the TextBox? It's got plenty of properties that identify which key has been pressed.

Upvotes: 4

Related Questions