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();
}
}
Summary. We used KeyCode in the KeyDown event to check against the Keys enumeration to detect the Enter key. It is possible to check many other keys.
Dot Net Perls is a collection of pages with code examples, which are updated to stay current. Programming is an art, and it can be learned from examples.
Donate to this site to help offset the costs of running the server. Sites like this will cease to exist if there is no financial support for them.
Sam Allen is passionate about computer languages, and he maintains 100% of the material available on this website. He hopes it makes the world a nicer place.
This page was last updated on Aug 20, 2024 (edit).