Windows Application - SPLessons

Win App Keyboard Events

Home > Lesson > Chapter 25
SPLessons 5 Steps, 3 Clicks
5 Steps - 3 Clicks

Win App Keyboard Events

Windows Application Keyboard Events

shape Description

When the user interacts with the system through the keyboard, then the keyboard events are raised. Each keyboard event requires an object called sender and KeyPressEventArgs as arguments.

shape Steps

To see the keyboard events follow the below steps.

shape Step 1

Create new windows application. Drag and drop two label controls onto the form and make the text property as empty. Then, the form looks like as shown in the below figure.

shape Step 2

Click on the form1. Then, properties of the form will be displayed in the properties window. Click on the Events Symbol as shown in the below figure. Then,that's going to bring the events window.

shape Step 3

See the keyboard events as shown in the above figure. Now, click on the white space beside the KeyDown, KeyUp and KeyPress events to raise the events. Then, the properties window will looks as shown in the below figure.

shape Step 4

Form1.cs will get the events and the code generates as shown in the below. [csharp] private void Form1_KeyPress(object sender, KeyPressEventArgs e) { } private void Form1_KeyDown(object sender, KeyEventArgs e) { } private void Form1_KeyUp(object sender, KeyEventArgs e) { } [/csharp]

shape Step 5

Now, write the code as shown in below. [csharp] using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace WindowsFormsApplication27 { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void Form1_Load(object sender, EventArgs e) { } private void Form1_KeyPress(object sender, KeyPressEventArgs e) { lblChar.Text = "Key Pressed: " + e.KeyChar; //displays the character which the user pressed } private void Form1_KeyDown(object sender, KeyEventArgs e) { lblValue.Text = "ASCII Value: " + e.KeyValue;//Dispalys the Ascci Value of the pressed key } private void Form1_KeyUp(object sender, KeyEventArgs e) { } } } [/csharp]

shape Step 6

Press f5 to run the application. The Following window will appear which is empty.

shape Step 7

Press any key. Then, the pressed key and its ASCII value will be displayed as follows.

shape Step 8

KeyUp Event is used when one want to do any action after the key release and to clear the labels after key release. Then, write the following code under the KeyUp Event. [csharp] private void Form1_KeyUp(object sender, KeyEventArgs e) { lblValue.Text = ""; lblChar.Text = ""; } [/csharp] These are the some of the key events. One can use these events in different ways.