Why does dialogresult work on button click but not on keydown?
I'm working on Desktop application.
Why does dialogresult work on button click but not on keydown?
I'm working on Desktop application.
Know the answer? Post it — somebody with the same question will find it here.
Sign in to answer this question
It is the same account you read, post and publish with — and you will come straight back to this page.
Rigobert GANDEPosted Jan 8, 2026, 12:12 PM
I have a message (information) box with a single OK button that sets isDefault = "true". Normally, when the message box appears and the user presses the Enter key, it should close in response to the associated Click() event.
The click works without the window closing correctly. But when I press the Enter key, the program crashes for no reason, without an error message.
Raghunath BhukanPosted Jan 8, 2026, 5:35 AM
Why
DialogResultworks on a Button clickIn WinForms:
When a button with
DialogResultis clicked:WinForms sets the form’s
DialogResultWinForms automatically closes the dialog
ShowDialog()returns that resultThis behavior is built into the Button control.
Why it does NOT work in
KeyDownWhen you handle a key press:
What happens?
The
DialogResultdoes get setThe form does NOT automatically close
ShowDialog()does not return yetBecause:
The correct way to handle
DialogResultin KeyDownOption 1: Set
DialogResultand close the formThis mimics what the Button does internally.
Option 2: Use
AcceptButton/CancelButton(BEST PRACTICE)Instead of handling
KeyDownmanually:Now:
EntertriggersbuttonOkEsctriggersbuttonCancelDialogResultworks automaticallyCleaner, more accessible, Standard Windows behavior
Important KeyDown Details (Another common pitfall)
If your
KeyDownnever fires, check these:1. Enable
KeyPreviewWithout this, focused controls (TextBox, etc.) eat the key events.
2. Use the correct event
KeyDown? good for Enter/EscKeyPress? character inputPreviewKeyDown? for special keys in some controlsSummary
Recommendation
If this is a dialog:
Sam HobbsPosted Jan 8, 2026, 2:56 AM
I need more information. Where does it not work? What button? What event is being handled?