KeyCode Property and KeyDownUse the KeyCode property in Windows Forms to detect the Enter key.
This page was last reviewed on Sep 25, 2022.
KeyCode handles key presses. You have a TextBox control on your Windows Forms application and need to detect Enter. With KeyCode, we can detect keys.
Solution info. Our solution involves the KeyDown event in our C# Windows Form and the KeyCode property. This code can make programs more interactive by detecting key presses.
First, click on your TextBox control in the form display. You will see the Properties Pane. Click on the lightning bolt icon. This icon stands for events: we use it to create events.
Then In the event tab, scroll to KeyDown, and double click in the space to the right. A new block of code will appear.
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) { } } }
Example 2. Here is the code that detects when Enter is pressed. 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. Here we see some values you can test against the KeyCode property. You can do this the same way as we tested Keys.Enter in the previous example.
Detail Indicates the shift key was pressed. You could use this to prevent a user from typing uppercase letters.
Detail Could use this to prevent user from tabbing out of a TextBox that isn't valid.
Detail Some of these are apparently original equipment manufacturer specific. They may vary on the keyboard being used.
Detail Useful for data entry applications. You could setup the program to detect whether the numeric pad is being used.
Summary. Here we saw how to use KeyCode in the KeyDown event to check against the Keys enumeration to detect the Enter key. You can also check many other keys.
Dot Net Perls is a collection of tested code examples. Pages are continually updated to stay current, with code correctness a top priority.
Sam Allen is passionate about computer languages. In the past, his work has been recommended by Apple and Microsoft and he has studied computers at a selective university in the United States.
This page was last updated on Sep 25, 2022 (rewrite).
© 2007-2024 Sam Allen.