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;
}
根据Cody Gray的建议,我将代码更改如下:
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 键按下。
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.
你可以处理您的控件的事件来处理这些击键并将它们设置为输入键。
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;
}
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)