Skip to content

Detecting Key Presses

Published On:
May 31, 2013
Last Updated:
May 31, 2013

WinForms

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

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.

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