Difference between revisions of "Keyboard Input in Visual C"
From WLCS
(2 intermediate revisions by the same user not shown) | |||
Line 3: | Line 3: | ||
# Add the following line of code to the '''public Form1()''' section: | # Add the following line of code to the '''public Form1()''' section: | ||
− | <source lang=" | + | <source lang="csharp"> |
this.KeyDown += new KeyEventHandler(Form1_KeyDown); | this.KeyDown += new KeyEventHandler(Form1_KeyDown); | ||
</source> | </source> | ||
Line 15: | Line 15: | ||
this.KeyDown += new KeyEventHandler(Form1_KeyDown); | this.KeyDown += new KeyEventHandler(Form1_KeyDown); | ||
} | } | ||
+ | </source> | ||
+ | |||
+ | Now add the following section of code '''after''' the public Form() section | ||
+ | |||
+ | <source lang="csharp"> | ||
+ | private void Form1_KeyDown(object sender, System.Windows.Forms.KeyEventArgs e) | ||
+ | { | ||
+ | switch (e.KeyCode) | ||
+ | { | ||
+ | case Keys.Left: | ||
+ | //add code that you want to run when the Left key is hit | ||
+ | break; | ||
+ | |||
+ | case Keys.Right: | ||
+ | //add code that you want to run when the Right key is hit | ||
+ | break; | ||
+ | |||
+ | case Keys.Up: | ||
+ | //add code that you want to run when the Up key is hit | ||
+ | break; | ||
+ | |||
+ | case Keys.Down: | ||
+ | //add code that you want to run when the Down key is hit | ||
+ | break; | ||
+ | |||
+ | default: | ||
+ | return; | ||
+ | } | ||
+ | } | ||
</source> | </source> |
Latest revision as of 13:40, 20 November 2009
- Select the Form and go to its Properties
- Change the KeyPreview property to True
- Add the following line of code to the public Form1() section:
this.KeyDown += new KeyEventHandler(Form1_KeyDown);
so it should look something like this:
public Form1()
{
InitializeComponent();
this.KeyDown += new KeyEventHandler(Form1_KeyDown);
}
Now add the following section of code after the public Form() section
private void Form1_KeyDown(object sender, System.Windows.Forms.KeyEventArgs e)
{
switch (e.KeyCode)
{
case Keys.Left:
//add code that you want to run when the Left key is hit
break;
case Keys.Right:
//add code that you want to run when the Right key is hit
break;
case Keys.Up:
//add code that you want to run when the Up key is hit
break;
case Keys.Down:
//add code that you want to run when the Down key is hit
break;
default:
return;
}
}