C# PROGRAMMING

Detecting Key Presses

Article by:
Date Published:
Last Modified:

WinForms

Use the following code to detect a key press when focus is on a particular object.

NOTE

There is different syntax for WPF.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
TextBox tb = new TextBox();

// Assign a new event handler
tb.KeyDown += new KeyEventHandler(tb_KeyDown);

// The event handler
private void tb_KeyDown(object sender, KeyEventArgs e) {
    if (e.KeyCode == Keys.Enter) {
        //Enter key is down

        //Capture the text
        if (sender is TextBox) {
            TextBox txb = (TextBox)sender;
            MessageBox.Show(txb.Text);
        }
    }
}

WPF

Non-Binding Method

Use the following code to detect a key press when focus is on a particular object.

NOTE

There is different syntax for WinForms.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
TextBox tb = new TextBox();

// Assign a new event handler
tb.KeyDown += new KeyEventHandler(tb_KeyDown);

private void tb_KeyDown(object sender, KeyEventArgs e) {
    if (e.Key == Key.Enter) {
        e.Handled = true;
        MessageBox.Show("You pressed Enter!");
    }
}

Authors

Geoffrey Hunter

Dude making stuff.

Creative Commons License
This work is licensed under a Creative Commons Attribution 4.0 International License .

Tags

    comments powered by Disqus