I have a modal Form with three Buttons, A B and C.
In addition, I have two Buttons: OK and Cancel. The OK Button's DialogResult property is set to DialogResult.OK and the Cancel Button DialogResult.Cancel.
The Form's AcceptButton and CancelButton properties are set to these Buttons.
Currently, the Form is closed when I press the ESC key but if I click the ENTER key when one of the other Buttons (A,B,C) is the Active Control, the Form is not closed. How can I overcome this?
I have two options:
Enter will always close the form (select the focused button and then close it),
The first Enter key press will select the focused button and a second
ENTERpress will close the Form. The problem is that maybe ButtonAwas selected but the user can go over ButtonBorCusing the arrow keys.
I can't set a DialogResult.OK to the other Buttons, because - in that case - a normal click will also close the Form and I have no way to detect if the event was called because of a Click event or the ENTER key...
If you want to activate the Default button - the Button that is set as the Form's AcceptButton - when another Button has the Focus, but not another Control, as a TextBox, that may want to accept the Enter key, you can override ProcessCmdKey (since pressing the Enter key doesn't raise the
KeyDownevent and theClickevent is raised before theKeyUpevent), verify whether the ActiveControl is of type Button (or other type of Controls you want to behave the same way) and set theActiveControlto yourAcceptButton.The Enter key is transferred to the
AcceptButtonand the Dialog is Closed, returningDialogResult.OK(since you have already set the Button'sDialogResultvalue):Note: this assuming that the Container Control is the same.
In case you just want to change the
ActiveControl, setting the Focus to theAcceptButton- so the User needs to press the Enter key twice to confirm, returntrueafter you have changed theActiveControl, to signal that the input has been handled: