Reputation: 22566
Good day,
I want to add key listeners in a forms user control. Which is included in a main form.
When a user presses a key in my application I want it to do some thing.
How do I go about doing this?
for example. If I pressed w then a popup would appear saying you pressed w.
I have tried this in my User Control Class;
private void UC_ControlsTank_KeyPress(object sender, KeyPressEventArgs e)
{
Console.Write("You pressed:" + e.KeyChar);
}
But when i press keys nothing seems to happen.
EDIT:
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_KeyPress(object sender, KeyPressEventArgs e)
{
MessageBox.Show(e.KeyChar.ToString());
}
}
Here is my form:
and here is how I linked it in visual studio:
Upvotes: 3
Views: 32130
Reputation: 8892
First of all before capturing KeyPress you have to set the KeyPreview
property of the Win Form to true
. Unless you set it to true KeyPress will not be captured.
Upvotes: 13
Reputation: 13618
There is a KeyPressed
event that you can use
This has System.Windows.Forms.KeyEventArgs e
that will tell you what key was pressed
Edit:
So I just tried this on a sample app and it worked fine
private void Form1_KeyPress(object sender, KeyPressEventArgs e)
{
MessageBox.Show(e.KeyChar.ToString());
}
Upvotes: 5
Reputation: 6103
Here is an Example ,
private void control_KeyDown(object sender, KeyEventArgs e)
{
switch (e.KeyData)
{
case Keys.W:
{
MessageBox.Show("you pressed w");
break;
}
case Keys.B:
{
MessageBox.Show("you pressed b");
break;
}
case Keys.F11:
{
MessageBox.Show("you pressed F11");
break;
}
case Keys.Escape:
{
this.Close();
break;
}
default:
{
break;
}
}
}
or
Reference this Overriding Keydown in a User Control using ProcessKeyPreview .
Upvotes: 2