Winform - Button - Prevent button pass Enter key to other control.

Truong Hoai 26 Reputation points
2022-04-10T04:00:26.57+00:00

I have a textbox1 and some more textbox with keypress event that change Enter key to Tab.
I have a button with click event: {textbox1.Focus();}.
The problem is that, when I press Enter key to fire button's Click event, the textbox1 gets focusing and cursor moves to next control (because textbox keypress event). It work well if I click on button by mouse.
Now I want pressing enter key on button without passing Enter key value to other controls.
Please help

Windows Forms
Windows Forms
A set of .NET Framework managed libraries for developing graphical user interfaces.
1,903 questions
{count} votes

Accepted answer
  1. Castorix31 85,806 Reputation points
    2022-04-10T12:09:59.4+00:00

    Instead of using Keypress events, you can use ProcessCmdKey to handle keys globally

    For example, to go to the next control on Enter, but only when the focus is not on the button (button1 in my test),
    you can do something like

        protected override bool ProcessCmdKey(ref Message msg, Keys keyData)
        {
            if (keyData == Keys.Enter)
            {  
                if (this.ActiveControl.Handle != button1.Handle)
                    this.SelectNextControl(this.ActiveControl, true, true, true, true);             
            }
            return base.ProcessCmdKey(ref msg, keyData);
        }
    

1 additional answer

Sort by: Most helpful
  1. Truong Hoai 26 Reputation points
    2022-04-11T03:26:09.93+00:00

    Hi @Castorix31 , Thanks for your support.
    However, On the message box, could you presss ENTER instead of CLICK. Show me the result please!


Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.