Geekpedia Tutorials Home

Building a C# Chat Client and Server

Building a C# Chat Client and ServerA step by step tutorial teaching you how to create your own chat client and chat server easily in C#, for local networks or the Internet.

in C# Programming Tutorials

Getting Hard Drive Information

Getting Hard Drive InformationA C# tutorial showing you how to make use of WMI to extract information on disk drives, such as model, capacity, sectors and serial number.

in C# Programming Tutorials

UPS Shipping Calculator

UPS Shipping CalculatorThis tutorial will teach you how to calculate the shipping cost based on the weight, height, length and depth of the box, the distance and the UPS service type.

in PHP Programming Tutorials

Create Your Own Rich Text Editor

Create Your Own Rich Text EditorCreating a Rich Text Editor using JavaScript is easier to do than you might think, thanks to the support of modern browsers; this tutorial will walk you through it.

in JavaScript Programming Tutorials
Search
Tutorials
Programming Tutorials
IT Jobs
From CareerBuilder

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.1 with 15 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)

{
MessageBox.Show("'A', and only A, was pressed.");
}


by Ryan on Wednesday, April 7th 2010 at 05:45 PM

I don't get it. I am making a game, and I would like to use the arrow keys to move my person. I imput this code:
private void EpicQuest_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.W)
{
MessageBox.Show("w");
}
}

just to test it, and It didn't to anything when i pushed 'w'. What happened.
I think to move it though, I will put something like

private void EpicQuest_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Up)
{
pnlYourGuy.Left ;
}
}
or something. Please help me as why it will not work!

by Ryan on Friday, April 9th 2010 at 11:50 AM

Ohh, I figured it out. I had it under the form's thing, and it is almost impossible to select the form.

by Erik on Saturday, May 1st 2010 at 12:36 PM

Some time ago,I programmed my keyboard to give the accent over a vowel, as in è for French texting.Can you please tell me how to remove this feature?
I am working on a Typing Tutor and the ' character does not appear until the second key stroke...which then shows '' so I have to delete one of the 's.All this is messing up my scores and is very frustrating as I cannot see my progress. The key is next to the 'Enter' key..

by Erik on Saturday, May 1st 2010 at 12:39 PM

Some time ago,I programmed my keyboard to give the accent over a vowel, as in è for French texting.Can you please tell me how to remove this feature?
I am working on a Typing Tutor and the ' character does not appear until the second key stroke...which then shows '' so I have to delete one of the 's.All this is messing up my scores and is very frustrating as I cannot see my progress. The key is next to the 'Enter' key..

by luciano on Saturday, May 1st 2010 at 05:45 PM

What you need to do is check the references you use Using .....
You need the IO reference.
Using System.IO;

by Carlos on Saturday, May 8th 2010 at 09:01 PM

hi. I want to use Console.Read() to get input from keyboard but first I want to initialize the variable and that the user can simply hit ENTER to confirm its value or delete it (backspace) to enter a new value.
Similar like editing text in a textbox with initial value but obviously without the visual object

thanks

by Luciano on Sunday, May 9th 2010 at 08:19 AM

Console.Read() is to get user Input not to read what keys has been pressed. you can do something like.

string rd;
try{
rd = Console.Read();

// messagebox with rd value.toString()
}catch(exption e){//error if not able to read or something

}

by Luciano on Sunday, May 9th 2010 at 08:19 AM

Console.Read() is to get user Input not to read what keys has been pressed. you can do something like.

string rd;
try{
rd = Console.Read();

// messagebox with rd value.toString()
}catch(exption e){//error if not able to read or something

}

by Carlos on Sunday, May 9th 2010 at 09:04 PM

@Luciano thanks for your answer. Maybe I should explain better

My goal is to modify individual fields of a record. Once I select the desired one, I need to get from keyboard its new contents and update it but I want to have its previous content as an initial value, so the user can decide to keep it by simply hitting ENTER or edit it to a new value by backspacing and typing

Hope I have explained better this time. Thanks again

Carlos

by luciano on Sunday, May 9th 2010 at 10:33 PM

Hi carlos I hope you don't mean a database record cause if that's so then, what you need todo is learn datasets you kan fill a dataset en retreieve data from a database than you kan edit a value in de recordand from there I don't know if there is a faster way cause i'm not that familiar with C#
at the website csharpstation.com you can learn dataset I think also here cause I find this the best website with tutorials for Csharp.
Dataset are really a mess. I don't like it i'm a php Mysql programmer I also program in Csharp also am I still learning if you want or need help you can always try and ask me I have sample code for datasets how to use them and how they work so If you like to see these codes or prefer a more private contact environment i;ll provide a link tomorrow online wich you only have to fill in your email after you've done that then it would be saved in my mail box and you will receive an email from me automatically with my info. but thats only if you want maybe we can learn from eachother

by deepak on Tuesday, June 8th 2010 at 07:07 AM

What to do to read the number of key pressed even the application is minimized or other application is running and that program is running in the background.

by Luciano on Tuesday, June 8th 2010 at 08:00 PM

You are talking about a keylogger to make one you will need something like a hook you will need to run the program as a process and do the reading.;)
you can also download keyloggers

by Brother on Monday, September 27th 2010 at 03:20 PM

i found this really helpfull thanx made a guitar hero game!!

by Brother on Monday, September 27th 2010 at 03:20 PM

i found this really helpfull thanx made a guitar hero game!!

by luciano on Monday, October 4th 2010 at 04:47 AM

thats nice where can I download and see it

by Mohsen on Tuesday, November 23rd 2010 at 06:43 AM

Key Input

by Rajendra on Wednesday, February 23rd 2011 at 12:56 AM

Please provide me sample programm that takes input from user and provide result..

by Rajendra on Wednesday, February 23rd 2011 at 12:56 AM

Please provide me sample programm that takes input from user and provide result..

by Rajendra on Wednesday, February 23rd 2011 at 01:06 AM

Please provide me sample programm that takes input from user and provide result..

by Lukasz on Wednesday, May 4th 2011 at 03:30 PM

Hiya, I am trying to write a simple game where you can control an aeroplane with keys, the idea is to move it smoothly across a screen while holding a key. But when I press (and hold) a key (lets say 'd') aeroplane moves a bit then stops and then it moves smoothly forward, is there any way to move it smoothly without any unnecessary stops ? I hope I was clear about it.

by Replica watches on Monday, November 21st 2011 at 12:39 AM

on the other hand belong to a category which at best can be called cheap and unworthy. They never give you your desired level of satisfaction. A fake watch is never an exact replacement of a designer or branded watch.

by magazine subscriptions to Japan on Monday, December 12th 2011 at 04:53 AM

thank u for providing me information on List View.
I want to know how i can display data in datalist in Newsletter layout and Thank you so much, this is easy to understand and fun to continue along with. I am a migrating VB.NET/C# Developer looking for an insight into VC .NET. I've found the VC tutorials on many sites to be confusing, and the navigation around the sites to be near impossible to use! Thanks once again.

by on Monday, January 9th 2012 at 05:21 AM

Once you have recreated the problem and captured these steps, you can save them to a file and send it to your support person, who can then open it up and view

by gdpoker.oneminutesite.it on Sunday, January 22nd 2012 at 11:13 AM

I don’t even know how I ended up here, but I thought this post was good. I do not know who you are but definitely you're going to a famous blogger if you are not already ;) Cheers!

by Marco Island Real Estate on Sunday, February 5th 2012 at 10:26 PM

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 .

by college paper writing service on Wednesday, March 7th 2012 at 01:13 PM

Your research just about this good post seems to be interesting and different people should use it for their phd thesis. And some scholars still utilize the support of the dissertation writing service.

by Law school personal statement on Monday, March 19th 2012 at 06:07 AM

What to do to read the number of key pressed even the application is minimized or other application is running and that program is running in the background.

by muhammad on Tuesday, July 31st 2012 at 07:13 AM

After making the KeyPress function how can i call it when the application starts

by case study writing on Thursday, September 20th 2012 at 05:05 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 multiple dropbox accounts on Tuesday, October 2nd 2012 at 02:22 AM

I make a visual element dat randomly changes a Letter on the keyboard

by invisible fence cost for one acre on Wednesday, October 24th 2012 at 06:33 AM

The event that occurs when the key is pressed is called KeyPress. It occurs between KeyDown and KeyUp, and therefore acts similar to KeyDown.

by water purification tablets where to on Thursday, November 1st 2012 at 05:49 AM

It occurs between KeyDown and KeyUp, and therefore acts similar to KeyDown.

by Margahayuland on Sunday, June 9th 2013 at 07:31 AM

The event that occurs when the key is pressed is called KeyPress
http://sooboos.com/margahayuland/margahayuland-42-tahun-membangun-ruang-hidup.php
http://sooboos.com/situs-berita/penting-panas-perlu-dan-seruu.php
http://sooboos.com
http://wadahpromoindonesia.blogspot.com/2013/05/margahayuland-42-tahun-membangun.html
http://tech-kinodeon.blogspot.com/2013/02/agen-bola-ligabet88-promo-bonus-100.html
http://tech-kinodeon.blogspot.com/2013/04/penting-panas-perlu-dan-seruu.html
http://tech-kinodeon.blogspot.com/2013/05/korek-api-gas-fighter-indonesia.html


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 >>
Ads

From the creators of Geekpedia, a revolutionary new coupon website!

BargainEZ has coupons codes, printable coupons, bargains and it is the leading source of Passbook coupons for iPhone and iPod touch devices.

Coupons
Discover Geekpedia
Other Resources