How can I determine in KeyDown that Shift + Tab was pressed

15,111

Solution 1

It can't work, because never both keys are pressed exactly in the same second.

You're right that your code doesn't work, but your reason is wrong. The problem is that the Tab key has a special meaning - it causes the focus to change. Your event handler is not called.

If you use a different key instead of Tab, then your code will work fine.


If you really want to change the behaviour of Shift + Tab for one specific control, it can be done by overriding ProcessCmdKey but remember that many users use the Tab key to navigate around the form and changing the behaviour of this key may annoy those users.

protected override bool ProcessCmdKey(ref Message msg, Keys keyData)
{
    if (DateTimePicker_BirthDate.Focused && keyData == (Keys.Tab | Keys.Shift))
    {
        MessageBox.Show("shift + tab pressed");
        return true;
    }
    else
    {
        return base.ProcessCmdKey(ref msg, keyData);
    }
}

Solution 2

If you are looking for a key press combination (Tab, then Shift) like Ctrl K + D you will have to use this modified example which was taken from MSDN social.

private StringBuilder _pressedKeys = new StringBuilder();

private void DateTimePicker_BirthDate_KeyDown(object sender, KeyEventArgs e)
{
    if (e.KeyCode == Keys.Tab)
    {
        _pressedKeys.Append("Tab");
        return;
    }

    if (e.Modifiers == Keys.Shift)
    {
        _pressedKeys.Append("Shift");
        return;
    }

    if (_pressedKeys.ToString()."TabShift")
    {
        MessageBox.Show("It works!");
         _pressedKeys.Clear();
    }
    else
    {
         _pressedKeys.Clear();
    }

    base.OnKeyDown(e);
}
Share:
15,111
hamze
Author by

hamze

Updated on August 01, 2022

Comments

  • hamze
    hamze almost 2 years

    How can I determine in KeyDown that + Tab was pressed.

    private void DateTimePicker_BirthDate_KeyDown(object sender, KeyEventArgs e)
    {
       if (e.KeyCode == Keys.Tab && e.Modifiers == Keys.Shift)
       {
           //do stuff
       }
    }
    

    can't work, because never both keys are pressed exactly in the same second. You always to at first the Shift and then the other one..