Use the KeyDown event on the KeyCode enumeration in Windows Forms. You have a TextBox control on your Windows Forms application. The TextBox allows your users to type letters into it, and you need to detect when a certain key like the Enter key is pressed. This will allow you to submit the contents of the TextBox to another layer of code.
Our solution involves the KeyDown event in our C# Windows Form. We use the KeyDown event for our code. Follow the following steps to add the KeyDown event to your TextBox. After the steps, there is an example of the KeyDown event handler, which will appear in your C# file.
using System;
using System.ComponentModel;
using System.Windows.Forms;
using System.Linq;
namespace WindowsProgramNamespace
{
public partial class TextWindow : Form
{
public TextWindow()
{
InitializeComponent();
}
private void textBox1_KeyDown(object sender, KeyEventArgs e)
{
}
}
}Here is the code that detects when Enter is pressed. The trick is to examine the KeyEventsArg e and check KeyCode. Keys is an enumeration, and it stores special values for many different keys pressed. KeyCode must be compared to Keys.
private void textBox1_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Enter)
{
// Enter (return) was pressed.
// Call a custom method when user presses this key.
AcceptMethod();
}
}| Keys enumeration value | If KeyCode equals, then do this |
| Keys.Shift | Indicates the shift key was pressed. You could use this to prevent a user from typing uppercase letters. |
| Keys.Tab | Could use this to prevent user from tabbing out of a TextBox that isn't valid. |
| Keys.OemPipe Keys.Oem* | Some of these are apparently original equipment manufacturer specific that vary
on the keyboard being used. Make sure to test these rigorously! |
| Keys.NumPad* | This could be useful for data entry applications. You could setup the program to
detect whether the numeric pad is being used, and if so, change the mode of the
program. (Not sure how this would work.) |
I feel that using the enumerated values on Keys is ideal, though, because it is clearer to read and simpler. It can be harder to add code that does this to other Key events. It is probably best to avoid using KeyPress to check the value of a key being pressed.
Use KeyCode in the KeyDown event to check against the Keys enumeration to detect the Enter key. Finally, you can check many other keys also by testing the e.KeyCode in the KeyDown event. If you need to detect Shift, Tab, or an Arrow key, this can be ideal.