Marty
Marty

Reputation: 3555

How to get KeyChar in WPF application

I have a simple app, where user types in text and presses Enter, then the text is displayed on big TV Screen.

The question : how to get e.KeyChar in WPF app, KeyUp Event ? Or is there another way ?

public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
            this.KeyUp += MainWindow_KeyUp;
        }

        private String Text;

        void MainWindow_KeyUp(object sender, KeyEventArgs e)
        {


            if (e.Key == Key.Enter)
            {
                TextLabel.Content = Text;
                Text = String.Empty;
            }
            else
            {
                Text += e.Key;
            }

        }

The results when I type in "test" is "TEST". Do I have to manually handle all the system keys ? What If I want to type "Test" -> now I get the result "RihgtShiftTEST". All I want is to accumulate a buffer of chars, and the display the text.

Upvotes: 0

Views: 3454

Answers (1)

Trevor Elliott
Trevor Elliott

Reputation: 11252

For reading text input it's best to use the following event:

http://msdn.microsoft.com/en-us/library/system.windows.uielement.ontextinput.aspx

The "Text" member of the TextCompositionEventArgs already provides high-level plain text and filters out all the nasty control characters, etc.

Upvotes: 2

Related Questions