Question

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

Was it helpful?

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

OTHER TIPS

That is how the AcceptButton property works. It specifies the button that is automatically clicked whenever you press <Enter>.

If you don't want this behaviour, don't set it as the AcceptButton. There is no other reason to do it.

You can remove AcceptButton from form and set the KeyPreview property on the form that'll handle its KeyDown event. There you can check for the Enter key and take the action accordingly.

This is one of the feature of the form i.e.

if button does not have a focus if you still want desired code to be executed when user click Enter...

Set the AcceptButton property of a form to allow users to click a button by pressing the ENTER even if the button does not have focus.

Regards.

Try This One In VB>net

  If CType(Me.ActiveControl, Button).Name = Button1.Name Then

        End If
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top