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.
Answer a question in the forums and earn +20 SHARP for every answer.
See unanswered questions
DevSocialUpcoming · 3rd editionAI Agents ConferenceDec 1–3, 2026Live onlineFree to attend5days leftRegister
Sam HobbsRank #107 · 20.5K reputationPosted Jan 7, 2026, 9:56 PM EST
I need more information. Where does it not work? What button? What event is being handled?
Raghunath BhukanRank #744 · 3.1K reputationPosted Jan 8, 2026, 12:35 AM EST
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:
private void Form_KeyDown(object sender, KeyEventArgs e) { if (e.KeyCode == Keys.Enter) { this.DialogResult = DialogResult.OK; } }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 formprivate void Form_KeyDown(object sender, KeyEventArgs e) { if (e.KeyCode == Keys.Enter) { this.DialogResult = DialogResult.OK; this.Close(); } }This mimics what the Button does internally.
Option 2: Use
AcceptButton/CancelButton(BEST PRACTICE)Instead of handling
KeyDownmanually:this.AcceptButton = buttonOk; this.CancelButton = buttonCancel;Now:
EntertriggersbuttonOkEsctriggersbuttonCancelDialogResultworks automaticallyCleaner, more accessible, Standard Windows behavior
Important KeyDown Details (Another common pitfall)
If your
KeyDownnever fires, check these:1. Enable
KeyPreviewthis.KeyPreview = true;Without 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:
Rigobert GANDE55 reputationPosted Jan 8, 2026, 7:12 AM EST
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.