开发者

C#: Trouble with Form.AcceptButton

开发者 https://www.devze.com 2022-12-17 00:17 出处:网络
I have a form with an button which is set as the AcceptButton of the form. The form has se开发者_如何学运维veral other controls. Now when I press Enter on other controls the form gets closed because o

I have a form with an button which is set as the AcceptButton of the form. The form has se开发者_如何学运维veral 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 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
0

精彩评论

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

关注公众号