Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Prevent WinForm AcceptButton handling Return key

Tags:

c#

winforms

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...

like image 824
Dave D Avatar asked Sep 21 '10 14:09

Dave D


2 Answers

While resetting the Forms AcceptButton while the TextBox has focus will work, I believe that the more appropriate solution is to use the TextBoxes AcceptsReturn Property.

If you set

myTextBox.AcceptsReturn = true;

the Form will not accept on pressing RETURN, but your TextBox can handle this itself.

This will avoid the need to reset the AcceptButton in multiple places in your code.

like image 90
NobodysNightmare Avatar answered Oct 19 '22 00:10

NobodysNightmare


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).

like image 25
Fredrik Mörk Avatar answered Oct 18 '22 23:10

Fredrik Mörk