Free C# Tutorials

home
Stay at Home and Learn

The KeyDown Event in C# .NET

 
Computer Tutorials List

 

 

 

 

The KeyDown event works in a similar way the MouseDown event - access an EventArg and write code to detect which key was pressed.

Return to Design View and locate the KeyDown events for the form:

The KeyDown Event

Now double click the name of the event to open up its code stub. You should see this:

C# Code stub for the KeyDown event

This time, instead of MouseEventArg we have a KeyEventArgs. After typing a letter "e", you'll see the IntelliSense list display a list of available options:

The IntelliSense list showing KeyEventArgs

The one you use to get at a particular key is the KeyData property. After a double equals sign, you then choose Keys from the IntelliSense list. Type another full stop and you'll see this list:

List of Keys on the Keyboard

The list contains all the letters, characters and keys from your keyboard.

Wrap all this up in an IF statement and you'll have this:

C# code to detect if the letter A was pressed

Run your form and test it out. You should see the message box appear when you press the letter "a" on your keyboard.

 

<-- The MouseDown Event | The Leave Event in C# -->

<--Back to the C# .NET Contents Page

View all our Home Study Computer Courses