Detect the Tab Key Press in TextBox

送分小仙女□ 提交于 2019-12-20 19:12:31

问题


I am trying to detect the Tab key press in a TextBox. I know that the Tab key does not trigger the KeyDown, KeyUp or the KeyPress events. I found: Detecting the Tab Key in Windows Forms of BlackWasp in the internet. They suggest to override the ProcessCmdKey, which I did, but it does not get triggered either. Is there a reliable way to detect the Tab Key press?

protected override bool ProcessCmdKey(ref Message msg, Keys keyData)
{

    bool baseResult = base.ProcessCmdKey(ref msg, keyData);

    if (keyData == Keys.Tab && textBox_AllUserInput.Focused)
    {
        MessageBox.Show("Tab key pressed.");
        return true;
    }
    if (keyData == (Keys.Tab | Keys.Shift) && textBox_AllUserInput.Focused)
    {
        MessageBox.Show("Shift-Tab key pressed.");
        return true;
    }

    return baseResult;
}

According to Cody Gray's suggestion, I changed the code as follows:

protected override bool ProcessCmdKey(ref Message msg, Keys keyData)
    {
        if (keyData == Keys.Tab && textBox_AllUserInput.Focused)
        {
            MessageBox.Show("Tab key pressed.");        }
        if (keyData == (Keys.Tab | Keys.Shift) && textBox_AllUserInput.Focused)
        {
            MessageBox.Show("Shift-Tab key pressed.");        }

        return base.ProcessCmdKey(ref msg, keyData);
    }

The problem is that it does not capture the Tab key press.


回答1:


Some key presses, such as the TAB, RETURN, ESC, and arrow keys, are typically ignored by some controls because they are not considered input key presses.

You can handle PreviewKeyDown event of your control to handle those key strokes and set them as input key.

private void textBox1_PreviewKeyDown(object sender, PreviewKeyDownEventArgs e)
{
    if(e.KeyData == Keys.Tab)
    {
        MessageBox.Show("Tab");
        e.IsInputKey = true;
    }
    if (e.KeyData == (Keys.Tab | Keys.Shift))
    {
        MessageBox.Show("Shift + Tab");
        e.IsInputKey = true;
    }
}



回答2:


you can used this code for tab are presed...

 private void input_KeyDown(object sender, System.Windows.Forms.KeyEventArgs e)
    { 
        //Check here tab press or not
        if (e.KeyCode == Keys.Tab)
        {
           //our code here
        }
        //Check for the Shift Key as well
        if (Control.ModifierKeys == Keys.Shift && e.KeyCode == Keys.Tab) {

        }
    }


来源:https://stackoverflow.com/questions/35914536/detect-the-tab-key-press-in-textbox

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!