2

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.

Joel Coehoorn
  • 399,467
  • 113
  • 570
  • 794
friggle
  • 3,362
  • 3
  • 35
  • 47
  • 1
    Did you try to just gobble the Enter key press in your javascript and not let it go to the server? – Roopesh Shenoy Mar 30 '12 at 21:46
  • @RoopeshShenoy: if the button is retaining focus then the browser isnt even seeing the keypress. – Sam Axe Mar 30 '12 at 21:52
  • 1
    Put a `-` directly in front of a search keyword to exclude pages with that word: but I doubt that would help you here. Judicious use of quotes to force word groups might work better. – Joel Coehoorn Mar 30 '12 at 22:02
  • 3
    Also: click-only buttons are evil. Those of us who know how to tab through a UI will hate you, and those who rely on screen readers will really hate you. – Joel Coehoorn Mar 30 '12 at 22:04

2 Answers2

4

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

Sam Axe
  • 33,313
  • 9
  • 55
  • 89
0

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.

Selçuk
  • 176
  • 1
  • 10