Despite me working with C# (Windows Forms) for years, I'm having a brain fail moment, and can't for the life of me figure out how to catch a user typing Ctrl + C into a textbox.
My application is basically a terminal application, and I want Ctrl + C to send a (byte)3
to a serial port, rather than be the shortcut for Copy to Clipboard.
I've set the shortcuts enabled
property to false on the textbox. Yet when the user hits Ctrl + C, the keypress event doesn't fire.
If I catch keydown, the event fires when the user presses Ctrl (that is, before they hit the C key).
It's probably something stupidly simple that I'm missing.
For me, it's not working with KeyDown event so I tried with PreviewKeyDown and it's worked.
I had a problem catching Ctrl + C on a
TextBox
byKeyDown
. I only gotControl
key when bothControl
andC
were pressed. The solution was usingPreviewKeyDown
:If you want to catch such combinations of keys in
KeyPress Event
look at this table here:in
Non-Printing Characters
section you can see the Dec numbers for each combination. For example, Dec number for Ctrl + C is3
. So you can catch it in KeyPress Event like this:Go ahead and use the KeyDown event, but in that event check for both Ctrl and C, like so:
Also, to prevent processing the keystroke by the underlying TextBox, set the SuppressKeyPress property to true as shown.
D'oh! Just figured it out. Out of the three possible events, the one I haven't tried is the one I needed! The KeyUp event is the important one:
Key events occur in the following order:
The KeyPress event is not raised by noncharacter keys; however, the noncharacter keys do raise the KeyDown and KeyUp events. Control is a noncharacter key.
You can check with this line of code:
if (e.KeyData == (Keys.Control | Keys.C))