Search code examples
c#formskeypressacceptbutton

C#: Trouble with Form.AcceptButton


I have a form with an button which is set as the AcceptButton of the form. The form has several other controls. Now when I press Enter on other controls the form gets closed because of the accept button on the form. Same goes for CancelButton. How do I handle this. I tried hooking on to keypress keydown event of the form and controls. None works. Any work around for this?

Thanks a ton, Datte


Solution

  • Not exactly sure about how you expect your form to function, but you could do something like the following to have a little more control over things:

        protected override bool ProcessCmdKey(ref Message msg, Keys keyData)
        {
            if (keyData == Keys.Enter)
            {
                // do something
            }
            if (keyData == Keys.Escape)
            {
                // do something else
            }
            return base.ProcessCmdKey(ref msg, keyData);
        }