Catching Ctrl + C in a textbox

2019-03-18 09:50发布

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.

8条回答
We Are One
2楼-- · 2019-03-18 10:39

Try the following: capture the up arrow and down arrow events. When you detect down arrow for CTRL, set a flag; when you detect up arrow, 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. :-)

查看更多
够拽才男人
3楼-- · 2019-03-18 10:42

I don't know if it's because some change in newer version or because I am trying to use this on ListBox, but there is no e.Control in KeyEventArgs e that I get from KeyDown.

I had to work around solution, I came up with this (it's not the prettiest one, but it works fine):

private List<Key> KeyBuff = new List<Key>();

private void ListBox_KeyDown(object sender, KeyEventArgs e)
{
    if (!KeyBuff.Exists(k => k == e.Key))
        KeyBuff.Add(e.Key);

    if (KeyBuff.Exists(k => k == Key.LeftCtrl || k == Key.RightCtrl) &&
        KeyBuff.Exists(k => k == Key.C))
    {
        // Desired detection
        Clipboard.SetText(SelectedText);
    }
}

private void ListBox_KeyUp(object sender, KeyEventArgs e)
{
    KeyBuff.Clear();
}
查看更多
登录 后发表回答