Reputation: 8982
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...
Upvotes: 12
Views: 5482
Reputation: 788
To get a complete working example, use the AcceptReturn=true of the TextBox as NobodysNightmare suggested and set the SuppressKeyPress to true to avoid bubble the event to the Form. To use the AcceptButton you need to set/reset the AcceptButton property when you enter/leave the texbox as Fredrik Mörk suggested.
var tb = new TextBox ...;
IButtonControl _oldAcceptButton = null;
tb.AcceptReturn=true;
tb.KeyDown += (s,e) => {
if(e.KeyCode==Keys.Enter) {
e.Handled=true;
//will not inform any parent controls about the event.
e.SuppressKeyPress=true;
//do your own logic
....
}
};
tb.Enter+=(s,e)=> {
_oldAcceptButton = AcceptButton;
AcceptButton = null;
};
tb.Leave+=(s,e)=>{
AcceptButton = _oldAcceptButton;
};
Upvotes: 2
Reputation: 3123
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.
Upvotes: 19
Reputation: 66604
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; };
Upvotes: 5
Reputation: 158389
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
).
Upvotes: 13