Zapnologica
Zapnologica

Reputation: 22566

C# key pressed listener in a Windows Forms UserControl

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: enter image description here

Upvotes: 3

Views: 32130

Answers (3)

Kurubaran
Kurubaran

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

David Pilkington
David Pilkington

Reputation: 13618

There is a KeyPressed event that you can use

Control.KeyPress Event

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

zey
zey

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

Related Questions