klemenhe
klemenhe

Reputation: 43

How to activate a button by pressing a specific key on the keyboard?

Hey I'm pretty new to programming and I'm wondering how to activate a button in Windows Forms by pressing a designated key, thank you.

I tried doing this:

    private void Form_KeyUp(object sender, KeyEventArgs e)
    {
        if (e.KeyCode == Keys.A)
        {
            btn_A.PerformClick();
            e.Handled = true;
        }
    }

But I can't seem to get it to work. Note that I am very new to all this so apologies in advance.

Upvotes: 2

Views: 1443

Answers (2)

FreaX
FreaX

Reputation: 94

Maybe easier. Create a KeyPress-Event of the Form and test for the specific key:

private void Form1_KeyPress(object sender, KeyPressEventArgs e)
    {
        //Test for Specific Key
        if(e.KeyChar == (char)Keys.Enter)
        {
            //Do Stuff like:
            button1.Enabled = true
        }
    }

Upvotes: 1

NotADeveloper
NotADeveloper

Reputation: 347

Have you tried setting KeyPreview to true?

Upvotes: 1

Related Questions