Search code examples
c#winformstextboxkeypress

How to detect Ctrl+1 key press in TextBox


I tried to detect ctrl + 1 key press in textbox on WinForm but the following code is not detecting the ctrl key press. Any suggestion will be helpful.

private void textBox1_KeyDown(object sender, KeyPressEventArgs e)
{
    if ((ModifierKeys & Keys.Control) == Keys.Control)
    {
        if (e.KeyChar == (char)Keys.D1)
            MessageBox.Show("1 get selected");
    }
}

Solution

  • Your (ModifierKeys & Keys.Control) is what's causing your trouble. I'd suggest to keep it simple :

    private void textBox1_KeyDown(object sender, KeyEventArgs e)
    {
        if (e.Control && e.KeyCode == Keys.D1)
        {
            MessageBox.Show("Selected !");
        }
    }