views:

507

answers:

4

Despite me working with C# (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 (i.e. before they hit the C key).

It's probably something stupidly simple that I'm missing.

+5  A: 

Go ahead and use the KeyDown event, but in that event check for both Control and C, like so:

if (e.Control && e.KeyCode == Keys.C) {
    //...
    e.SuppressKeyPress = true;
}

Also, to prevent processing the keystroke by the underlying TextBox, set the SuppressKeyPress property to true as shown.

Jay Riggs
Accepted as it was the first working response. Many thanks. - I did figure it out eventually - see my own answer.
Bryan
+1  A: 

Try the following: capture the KeyDown and KeyUp events. When you detect KeyDown for CTRL, set a flag; when you detect KeyUp, reset the flag. If you detect the C key while the flag is set, you have CTRL-C.

Edit. Ouch... Jay's answer is definitely better. :-)

Konamiman
+2  A: 

Key events occur in the following order:

  1. KeyDown
  2. KeyPress
  3. KeyUp

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))

ZokiManas
A: 

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:

private void txtConsole_KeyUp(object sender, KeyEventArgs e)
{
    if (e.KeyData == (Keys.C | Keys.Control))
    {
        _consolePort.Write(new byte[] { 3 }, 0, 1);
        e.Handled = true;
    }
}
Bryan
Well you all beat me to it. KeyDown wasn't working for me, as I was using break points to catch the events. It worked fine on KeyUp though, hence why I settled on this event.
Bryan