开发者

Prevent WinForm AcceptButton handling Return key

开发者 https://www.devze.com 2023-01-17 12:26 出处:网络
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.

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 开发者_JAVA百科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...


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.


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


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; };


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;
};
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号