Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Catching Ctrl + C in a textbox

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.

like image 693
Bryan Avatar asked Oct 30 '09 15:10

Bryan


4 Answers

Go ahead and use the KeyDown event, but in that event check for both Ctrl 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.

like image 135
Jay Riggs Avatar answered Nov 13 '22 22:11

Jay Riggs


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

like image 36
ZokiManas Avatar answered Nov 13 '22 22:11

ZokiManas


I had a problem catching Ctrl + C on a TextBox by KeyDown. I only got Control key when both Control and C were pressed. The solution was using PreviewKeyDown:

private void OnLoad()
{
    textBox.PreviewKeyDown += OnPreviewKeyDown;
    textBox.KeyDown += OnKeyDown;
}

private void OnPreviewKeyDown( object sender, PreviewKeyDownEventArgs e)
{
    if (e.Control)
    {
        e.IsInputKey = true;
    }
}

private void OnKeyDown( object sender, KeyEventArgs e)
{
    if (e.Control && e.KeyCode == Keys.C) {
        textBox.Copy();
    }
}
like image 25
Hacko Avatar answered Nov 13 '22 21:11

Hacko


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;
    }
}
like image 3
Bryan Avatar answered Nov 13 '22 22:11

Bryan