joi, 4 august 2011

Ignore Enter Key Press for .NET Button

According to the documentation found on MSDN, "A Button can be clicked by using the mouse, ENTER key, or SPACEBAR if the button has focus."
It took a while until I have found how to disable the Enter and Spacebar keys to produce the Click event for a form button that has focus. The solution is to override the ProcessCmdKey method in a derived class and catch the Enter key press in that method and return before it gets to be processed by the method in the Button base class. Here is the basic class I used to accomplish this.

/// <summary>
/// A class that inherits the System.Windows.Forms.Button class and ignores
/// the ENTER key press that also triggers the click event.
/// </summary>
internal class ButtonNoEnter : System.Windows.Forms.Button
    protected override bool ProcessCmdKey( ref Message msg, Keys keyData )
       if( keyData == Keys.Enter || keyData == Keys.Space )
            return true;
      return base.ProcessCmdKey( ref msg, keyData );

Niciun comentariu:

Trimiteți un comentariu