A button that can ONLY be used by clicking. No Enter, no Return. Just clicks

551 Views Asked by At

I wish I could throw a ! on a Google search, and turn up the opposite answer. Looking for having buttons NOT activated by keypresses only turns up folks who need their buttons activated by keypresses.

I'm having issues with buttons on a form being accidentally triggered by Enter & Return keypresses. They tend to have Focus on them, and keep firing while trying to press Enter in an unrelated part of the form (on a WebBrowser).

I thought to defend them with

 if (!btnButton1.Focused) { return; }

but as I said, Focus tends to linger on them, and this doesn't help me out

I want my buttons to only be usable through by clicks.

2

There are 2 best solutions below

2
On BEST ANSWER

Just subscribe to the Button.MouseClick event instead of Button.Click.

0
On

In your Page_Load event:

myButton.Attributes.Add("onkeypress", "return noEnter(event)");

And in your page add this javascript code:

function noEnter(e) {
    if (e.keyCode == 13) {
        return false;
    }
}

That should do the trick. I hope this is helpful.