Jonn Ballehr
Jonn Ballehr

Reputation: 23

How to get a clickable button to also activate upon a keypress? (Windows Form C#)

I have a regular button called Btn_Down that activates when clicked, but I also want it to activate when the 'S' key is pressed. Can anyone help me out with this?

Upvotes: 2

Views: 64

Answers (1)

DotNet Developer
DotNet Developer

Reputation: 3018

Subscribe to KeyDown event of form control which contains your button and add following code

private void Form1_KeyDown(object sender, KeyEventArgs e)
{
    switch (e.KeyData)
    {
        case Keys.S:
            button1_Click(this, EventArgs.Empty);
            //Or
            //button1.PerformClick();
            break;
    }
}

Set form's KeyPreview property to true. These settings should give the effect you want.


private void Form1_KeyPress(object sender, KeyPressEventArgs e)
{
    switch (e.KeyChar)
    {
        case 'S':
        case 's':
            button1_Click(this, EventArgs.Empty);
            //Or
            //button1.PerformClick();
            break;
    }
}

Upvotes: 3

Related Questions