Search code examples
c#winformskeypress

How to Press 3 Keys at a Time using KeyPress?


Is it possible to get 3 keys at time on KeyPress? I want to get Ctrl + H + T . . .

I tried the ff:

if (e.KeyCode == Keys.H && e.Modifiers == Keys.Control)
{
    if (e.KeyCode == Keys.T && e.Modifiers == Keys.Control)
    {
        Console.WriteLine("^");
    }
}

But seems not work. I guess e.KeyCode returns only one key at a time? So I'm still thinking on how I can do it ... or storing previous key to variable possible? Thanks in advance


Solution

  • This should work (I tested it and it seems to do what you need).

    If you press Ctrl+H, it sets a boolean variable. Then if you press Ctrl+T immediately afterwards, it'll detect that both were pressed in succession. If you press anything other than Ctrl+T, it'll set the flag back to False.

    private bool isCtrlHPressed;
    
    private void txt_callerName_KeyDown(object sender, KeyEventArgs e)
    {
        if (isCtrlHPressed && e.KeyCode == Keys.T && e.Modifiers == Keys.Control)
            Console.WriteLine("^");
    
        isCtrlHPressed = (e.KeyCode == Keys.H && e.Modifiers == Keys.Control);
    }