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

Time:05-30

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?

CodePudding user response:

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;
    }
}
  • Related