Tuesday, April 5, 2011

Prevent WinForm AcceptButton handling Return key

I have a form with a button hooked up to the AcceptButton property so that logic occurs and the form is closed when the user presses the Return key.

On that form I display a dynamically created TextBox that appears when the user double-clicks a certain area then hides when the user presses Return.

How do I prevent the form from processing the key press when the user presses Return while the TextBox has focus?

I was attempting to say the key press was handled in the TextBox.KeyDown event handler via KeyEventArgs.Handled but the Button.Click event of my accept button is being fired first...

From stackoverflow
  • Use the Enter and Leave events of the TextBox to set the AcceptButton property to null (on Enter) and re-assign the button to it (on Leave).

    Dave : It's so obvious once someone points it out! :)
  • Set the AcceptButton property to null when you create that textbox, and set it back to the normal value when it loses focus:

    var myTextBox = new TextBox ... ;
    AcceptButton = null;
    
    myTextBox.Leave += (s, e) => { AcceptButton = btnOK; };
    

0 comments:

Post a Comment