Search code examples
c#winformskeypress

WFA keypress event not working after adding click event


The idea is that I want to record the reaction time of one user by displaying an object or making an audio, and then the users presses one button to see how fast he was.

I tried going step-by-step. I simply made an WFA that listens the keyboard, and when a key is pressed, it displays a message, like so:

    public Form1()
    {
        InitializeComponent();
        label1.Text = "";
    }

    private void Form1_Load(object sender, EventArgs e)
    {
        this.KeyDown += new KeyEventHandler(Form1_KeyDown);
    }

    private void Form1_KeyDown(object sender, KeyEventArgs e)
    { 
        if (e.KeyCode == Keys.A)
        {
            label1.Text = "The A key was pressed";
        }
    }

Simple.

But, when I add a button - so that I can now display an object, it's all going wrong. I don't know why it doesn't work.

The idea is that when I make the button component, it will add the method button_Clicked. I have tried in a million ways to get a key, but, after the button was added, it doesn't work. It doesn't matter when I press the key: before the click, after, in the same time.

I thought that maybe when I click, all the focus goes to the button, and so, if I press a key, i thought that the key is associated with the button, so I made a new method: button_Keydown, and made the same thing as in Form1_Load. It doesn't work like this either.

I have tried for the past 3 hours to figure it out, to change the code. But I couldn't figure it out. Any suggestions?


Solution

  • Look in the Form's Events and make sure you have your KeyDown function selected. That should do the trick.

    Regards.