Geekpedia Programming Tutorials






Getting input from keyboard

Getting the current pressed key on the keyboard, key combinations, key value and combining mouse clicks with key pressing.

On Friday, May 28th 2004 at 12:09 PM
By Andrew Pociu (View Profile)
*****   (Rated 4.3 with 12 votes)
Contextual Ads
More C# Resources
Advertisement

When you type on the keyboard the keystrokes go to a particular application, the active application.
The active application receives the input from the keyboard. This means the application has input focus.

There are two events for a key on a keyboard, when the key is pressed and when it is released. No it's not a single event as you might expect if you have no prior programming experience, in shooter games for example when you keep the forward key pressed (KeyDown) the player goes forward, and when it isn't pressed (KeyUp) the player stays put.
The event that occurs when the key is pressed is called KeyPress. It occurs between KeyDown and KeyUp, and therefore acts similar to KeyDown.

Similar to the way we handle OnPaint and other events we also handle the OnKeyDown event (because we want the event to occur when the key is pressed and not when it is released) by overriding it.

Try the code below and test it. You will understand the role of each property.


protected override void OnKeyDown(KeyEventArgs keyEvent)
{
    // Gets the key code
    lblKeyCode.Text = "KeyCode: " + keyEvent.KeyCode.ToString();

    // Gets the key data; recognizes combination of keys
    lblKeyData.Text = "KeyData: " + keyEvent.KeyData.ToString();

    // Integer representation of KeyData
    lblKeyValue.Text = "KeyValue: " + keyEvent.KeyValue.ToString();

    // Returns true if Alt is pressed
    lblAlt.Text = "Alt: " + keyEvent.Alt.ToString();

    // Returns true if Ctrl is pressed
    lblCtrl.Text = "Ctrl: " + keyEvent.Control.ToString();

    // Returns true if Shift is pressed
    lblShift.Text = "Shift: " + keyEvent.Shift.ToString();
}



How do I find out when the user presses a specific key?
As you probably imagine, this will be easily accomplished using 'if'.


if (keyEvent.KeyCode == Keys.A)
{
    MessageBox.Show("'A' was pressed.");
}



Probably most beginners would be tempted to do this:


if (keyEvent.KeyCode == "A")
....



which is definitely incorrect because we can't compare System.Windows.Forms.Keys to a string.

Also note that in the example we are using 'keyEvent.KeyCode', that means that even if we have other shift keys pressed (Alt, Ctrl, Shift, Windows...) simultaneous with A, the if condition returns true because it doesn't recognize key combinations.
If we want to ignore key combinations (Alt+A, Ctrl+Shift+A), etc. we need to use 'keyEvent.KeyData' of course:


if (keyEvent.KeyData == Keys.A)
{
    MessageBox.Show("'A', and only A, was pressed.");
}



When you right click on a file in Windows Explorer and you have the Shift key pressed you get the additional 'Open with...' item in the menu. This and many others are cases when you need to use the mouse button together with the keyboard.

The following code will change the background color of the form only if the form is clicked while the Ctrl key on the keyboard is pressed. If the Ctrl key is unpressed and the form is clicked nothing happens.


private void Form1_Click(object sender, System.EventArgs e)
{
    Keys modKey = Control.ModifierKeys;
    if(modKey == Keys.Control)
    {
        this.BackColor = Color.Yellow;
    }
}


If you have further questions feel free to ask them and also check the following pages at MSDN:

KeyUp Event
KeyPress Event
KeyDown Event
Digg Digg It!     Del.icio.us Del.icio.us     Reddit Reddit     StumbleUpon StumbleIt     Newsvine Newsvine     Furl Furl     BlinkList BlinkList

Rate Rate this tutorial
Comment Current Comments
by Vijay on Sunday, May 15th 2005 at 04:33 PM

Nice article.
Can you please post tutorial to show "How to Cancel Key Stroke"
For instance, If I want to cancel non Numeric characters being entered in textBox.

by Andrei Pociu on Sunday, May 15th 2005 at 04:54 PM

Hello,

That's a good addition for this tutorial.
You can cancel they key stroke from the KeyDown event or from the TextChanged event of the TextBox, as in the following example:

Match StrC = Regex.Match(txtC.Text, ("^-+$|^[0-9]+$"));
bool ParseRes = Double.TryParse(txtC.Text, System.Globalization.NumberStyles.Number, System.Globalization.NumberFormatInfo.CurrentInfo, out DblNum);
if (ParseRes == false & txtC.Text != "" & StrC.Success == false)
{
txtC.Text = "";
txtC.Focus();
txtC.BackColor = Color.FromArgb(255, 237, 237);
}

Here I'm using both RegEx and the TryParse() method to check if there is a valid number entered in the TextBox named txtC.

by Ali on Thursday, August 4th 2005 at 02:54 PM

hi, How do i override the keyUp event for my Rich text box, so that it only prints my specified characters and does not print the actual character pressed on the keyboard.

by Umer Ashraf on Friday, September 23rd 2005 at 06:21 PM

To replace character 'a'



private void textBox1_KeyPress(object sender, System.Windows.Forms.KeyPressEventArgs e)
{


//Check if
if (e.KeyChar =='a')
{
e.Handled =true; // This will cancel the keystorke as asked before
textBox1.Text +='\u0634'; //Print unicode char instead of 'a'
}
}

by X on Tuesday, February 7th 2006 at 10:11 AM

What includes do you have w/ the file

by hardik on Monday, March 13th 2006 at 12:45 AM

HI ,
My application requies to generate a log file that contains the logs of the keys pressed ,while my application is running .This is irrespective of the active window .For instance if Word is open and keys are pressed i should be able to get the sequence of keys pressed .
Since the events of keys pressed is handle by the acive window I am not able to get the key strokes pressed.

I believe I shall have to capture the key events at the system level.
How do i do this using eVC .

by David on Thursday, May 11th 2006 at 03:43 PM

hi,

for VB:

if you dont want the key Up to be processed in your control use the following code

Private Sub textbox1_KeyDown(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles textbox1.KeyDown
If e.KeyCode = Keys.Up Then
e.SuppressKeyPress = True
End If
end sub

by jawad on Wednesday, July 26th 2006 at 06:53 PM

hi if i want to find that which key are pressed in other windows instead of my application form means spying of my computer or any other computer on network than how can i do this
or simply how can i record keyboard inputs and record them in a file all keys for using any application active window and also my program is hiddden so what is the procedure for this.

by mohamed on Wednesday, August 23rd 2006 at 01:39 AM

what if i want to generate and capture the flying window keys' events,thx

by jeevan on Thursday, April 5th 2007 at 12:23 AM

hi,
Can i take inputs by pressing two keys at same time, like A+J pressing it simultaneously how do i input to the code.

by Yellow_Yackets on Thursday, March 12th 2009 at 04:21 PM

How about receiving key input into two controls simultaneously? is it possible..? how?

by razv on Saturday, April 4th 2009 at 07:10 AM

Nice tutorial. But how about getting input from keyboard without the form being active? like a keylogger

by kizzyjhil on Friday, August 21st 2009 at 06:43 AM

nice tutorial.but how about Getting Input From Keyboard when computing a grade in a form of bufferedReader and JOption?

by minyeko on Sunday, October 4th 2009 at 08:09 AM

I want to know how to use keypad ... thanks

by Luciano on Tuesday, October 6th 2009 at 08:01 PM

Hi I want to make a type programma for people who want to learn how to type how kan I make a visual element dat randomly changes a Letter on the keyboard

by maroot on Tuesday, January 12th 2010 at 02:25 AM

I want to know how to use Arrow keys Or direction Keys... thanks

by luciano on Tuesday, January 12th 2010 at 11:37 AM

Like the tutorial above says :

if (keyEvent.KeyData == Keys.A)<-- (the " A" can be replace by another character when you type Keys. you will get a list from visual studio there you can select all the possibilities)
-->
<-- what to do if condition is true -->
{
MessageBox.Show("'A', and only A, was pressed.");
}



Comment Comment on this tutorial
Name: Email:
Message:
Comment Related Tutorials
There are no related tutorials.

Comment Related Source Code
There is no related source code.

Jobs C# Job Search
My skills include:
Enter a City:

Select a State:


Advanced Search >>
Latest Tech Bargains

Advertisement

Free Magazine Subscriptions

Today's Pictures

Today's Video

Other Resources

Latest Download

Latest Icons