简体   繁体   中英

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

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.

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

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 ie

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM