JackIta
JackIta

Reputation: 119

Remove possibility to trigger a button with a keyboard input

I have a standard button, with nothing interesting in it, and everything works perfectly:

private void Button_Click(object sender, EventArgs e)
{
    //Whatever, is not important what's in it
}

The problem is, when I click on a button, if after that I press for example enter key or the space key, it will trigger the button as if I clicked it.

I tried messing with the properties and is no help either. How do I prevent that from happening in a (possibly) easy way?

Answer for anyone who needs it(to put inside the button):

if (e is MouseEventArgs)
{
     //what you want in for the button to do
}

Upvotes: 1

Views: 258

Answers (2)

B Hawkins
B Hawkins

Reputation: 25

Although Matteo Umili has provided an effective solution I thought I would share this solution in case anyone finds it useful:

Simply remove the focus away from the button to another control. This solution requires another control for the focus to switch to. In my example, I am using a label.

    private void button2_Click(object sender, EventArgs e)
    {
        label1.Focus();
    }

Upvotes: 0

Matteo Umili
Matteo Umili

Reputation: 4017

You can check the type of the given EventArgs, if the button is clicked e is a MouseEventArgs (and will contain info about the click), otherwise is just a EventArgs

private void button1_Click(object sender, EventArgs e)
{
    if (e is MouseEventArgs)
    {
        // Is mouse click
    }
    else
    {
        // Not mouse click...
    }
}

Upvotes: 2

Related Questions