In my application I have added keyboard shortcuts (an event handler) to a TextBox. One is Ctrl+H, which shows a Find & Replace popup.
In the KeyDown event handler of my form I check for the Ctrl+H keypress:
case Keys.H:
ShowFindReplaceDialog(true); // This line makes the SuppressKeyPress not work
e.SuppressKeyPress = true;
break;
Now, Ctrl+H is a standard keyboard shortcut that is equivalent to pressing backspace, so I need to suppress that.
The problem is that showing a popup causes the suppression not to work. So the popup is shown, and after it closes I see that the backspace (Ctrl+H) key still comes through.
How can this be made to work?
N.B. For completeness' sake: you run into this same issue with a MessageBox, it's all ShowDialog underneath.
Yes, that's because you call ShowDialog(). That's a blocking call so the e.SuppressKeyPress statement doesn't get executed until after the dialog is closed. And ShowDialog pumps a message loop, DoEvents style, so the keystroke message gets dispatched as normal and triggers the KeyPress event.
The most straight-forward workaround is to delay displaying the dialog until the message handling is complete. Elegantly done with Control.BeginInvoke(), like this:
case Keys.H:
this.BeginInvoke(new Action(() => ShowFindReplaceDialog(true)));
e.SuppressKeyPress = true;
break;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With