public class CustomTextBox : System.Windows.Forms.TextBox
{
protected override bool IsInputKey(Keys keyData)
{
if (keyData == Keys.Return)
return true;
return base.IsInputKey(keyData);
}
}
然后可以通过以下方式使用KeyDown事件:
CustomTextBox ctb = new CustomTextBox();
ctb.KeyDown += new KeyEventHandler(tb_KeyDown);
private void tb_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Enter)
{
//Enter key is down
//Capture the text
if (sender is TextBox)
{
TextBox txb = (TextBox)sender;
MessageBox.Show(txb.Text);
}
}
}
4 回答
KeyDown或KeyUp .
您还可以在WPF中使用PreviewKeyDown:
或者在C#中:
然后在附加课程中:
KeyDown事件仅通过“普通”输入键在标准TextBox或MaskedTextBox中触发,而不是ENTER或TAB等 .
通过重写IsInputKey方法,可以获得像ENTER这样的特殊键:
然后可以通过以下方式使用KeyDown事件:
在WPF中,TextBox元素将无法使用“Enter”按钮创建KeyUp事件,直到您不设置属性:AcceptsReturn =“True” .
但是,它将解决在TextBox元素中处理KeyUp事件的问题 . 按“ENTER”后,您将在TextBox中获得一个新的文本行 .
我通过使用Bubble事件策略解决了使用TextBox元素的KeyUp Event的问题 . 这很简单 . 您必须在某个(任何)父元素中附加KeyUp事件处理程序:
XAML:
C#逻辑部分(KeyUp事件处理程序附加到网格元素):
结果:
Image with result