检测文本框中的Tab键按下 [英] Detect the Tab Key Press in TextBox

查看:57
本文介绍了检测文本框中的Tab键按下的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试检测 TextBox 中的 Tab 键按下.我知道Tab键不会触发 KeyDown KeyUp KeyPress 事件.我发现:在Internet中检测BlackWasp的Windows窗体中的Tab键.他们建议覆盖我做过的ProcessCmdKey,但也不会触发.是否存在检测Tab键按下的可靠方法?

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);
    }

问题在于它无法捕获Tab键.

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

推荐答案

某些按键,例如 TAB RETURN ESC 和箭头键通常被某些控件忽略,因为它们不被视为输入键按下.

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;
    }
}

这篇关于检测文本框中的Tab键按下的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆