dattebayo
dattebayo

Reputation: 2072

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

Upvotes: 1

Views: 4080

Answers (5)

Vibin Jith
Vibin Jith

Reputation: 931

Try This One In VB>net

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

        End If

Upvotes: -2

Amit
Amit

Reputation: 3478

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.

Upvotes: 0

Faisal
Faisal

Reputation: 4264

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.

Upvotes: 1

Ken
Ken

Reputation: 1880

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

Upvotes: 3

Aaronaught
Aaronaught

Reputation: 122624

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.

Upvotes: 4

Related Questions