Skip to main content

Detecting Key Presses

Geoffrey Hunter
mbedded.ninja Author

WinForms

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

note

There is different syntax for WPF.

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.

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!");
}
}