Setting AcceptButton to None still closes the form on ENTER

427 Views Asked by At

I have a MDI windows forms application and my child forms mostly have "OK" and "Cancel" buttons. However I do not want them to be activated with ENTER/ESC keys to prevent accidental saves/aborts. So, the form has both AcceptButton and CancelButton set to none. The ESC button indeed does nothing, but the ENTER button still closes the form by "clicking" on the first button found, sorted by TabOrder.

Why is this so? Must I really start doing workarounds and catching the ENTER key?

Added: OK, this is way weirder. Reflector tells me that apparently if the first control by Tab Order (well, actually the control which is active by default when the form is opened) is a button, then it gets assigned as the default control. Otherwise nothing happens. Now the question changes to: WTF?!

3

There are 3 best solutions below

1
On

It sounds that as OK button is the first control in the tab order, it automatically gets keyboard focus when the form is loaded, meaning that hitting enter will click it. If you would prefer the keyboard focus to go to another control, try setting the ActiveControl property to another element on the forum.

Button okButton = new Button();
TextBox someOtherControl = new TextBox();

// Add controls to form.
this.Controls.Add(okButton);
this.Controls.Add(someOtherControl);

// Specifically set the ActiveControl on the form.
this.ActiveControl = someOtherControl;
0
On

I was just stuck on the same problem. Was not using WinForms for a long time, thought can I be missing something in such simple thing?

In my case, I want "Ok" button to be invisible (or disabled) while some task runs, and then appear in the end... So at the start, only "Cancel" is shown, and it's always the "accept"! No matter if I set AcceptButton to "Ok", or to "None", and after the "Ok" appears on form - still "Cancel" acts on Enter. If both buttons are always visible and enabled - it's correct. Well... I thought it was correct, but now after reading this, I tried switching buttons order and yes, it's the first button that is always "accept".

It appears that Form.AcceptButton is just obsolete and unused now. Form.CancelButton is working still, though. I know this is the way how it works in HTML, but in WinForms... I have the same "wtf" question. .NET 4.5.

0
On

Exept all the designer sets DialogResult property to your buttons, and don't clear them, when you set AcceptButton/CancelButton property to None. So, you have to do it manually (in your code or in designer).

Button okButton = new Button();

// some code here

okButton.DialogResult = DialogResult.None;