[英]C# - How can I block the typing of a letter on a key press?
我有一个带有OnKeyPress事件的文本框。 在此文本框中,我只希望输入数字,对于某些特定的字母,例如t或m,我想执行一个代码,而无需在文本框中键入该字母。 我正在尝试做的小样本:
//OnKeyPressed:
void TextBox1KeyDown(object sender, KeyEventArgs e)
{
if(e.KeyCode == Keys.T || e.KeyCode == Keys.M) Button1Click(this, EventArgs.Empty);
}
不幸的是,这不会阻止字母的输入。
将KeyEventArgs的SuppressKeyPress属性设置为true,如下所示:
private void TextBox1KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.T || e.KeyCode == Keys.M)
{
e.SuppressKeyPress = true;
Button1Click(this, EventArgs.Empty);
}
}
您可以始终在keyDown事件上运行TryParse,以便在输入数据时进行验证。 它为用户节省了额外的UI交互。
private void TextBox1KeyDown(object sender, KeyEventArgs e)
{
int i;
string s = string.Empty;
s += (char)e.KeyValue;
if (!(int.TryParse(s, out i)))
{
e.SuppressKeyPress = true;
}
else if(e.KeyCode == Keys.T || e.KeyCode == Keys.M)
{
e.SuppressKeyPress = true;
Button1Click(this, EventArgs.Empty);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.