views:

456

answers:

5

Hi all,

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

+3  A: 

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.

Aaronaught
+1  A: 

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);
    }
Ken
+1  A: 

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.

Faisal
A: 

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.

Amit
A: 

Try This One In VB>net

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

        End If
Vibin Jith
This code is incorrect (apart from being VB.NET code instead of C# code -- see the question tags). You can't specify the target type as a string when type-casting. Another way of writing this would be `Object.ReferenceEquals(Me.ActiveControl(), btnSubmit)`.
stakx
check it? i edited.
Vibin Jith