C#-如何阻止在按键上键入字母?
我有一个带有OnKeyPress事件的文本框。在这个文本框中,我只希望输入数字,对于一些特定的字母,如t或m,我希望在文本框中不输入该字母的情况下执行代码。我正在尝试做的小样本:C#-如何阻止在按键上键入字母?,c#,winforms,input,block,letter,C#,Winforms,Input,Block,Letter,我有一个带有OnKeyPress事件的文本框。在这个文本框中,我只希望输入数字,对于一些特定的字母,如t或m,我希望在文本框中不输入该字母的情况下执行代码。我正在尝试做的小样本: //OnKeyPressed: void TextBox1KeyDown(object sender, KeyEventArgs e) { if(e.KeyCode == Keys.T || e.KeyCode == Keys.M) Button1Click(this, EventArgs.
//OnKeyPressed:
void TextBox1KeyDown(object sender, KeyEventArgs e)
{
if(e.KeyCode == Keys.T || e.KeyCode == Keys.M) Button1Click(this, EventArgs.Empty);
}
不幸的是,这不会阻止字母的输入。将SuppressKeyPress属性从KeyEventArgs设置为true,如下所示:
private void TextBox1KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.T || e.KeyCode == Keys.M)
{
e.SuppressKeyPress = true;
Button1Click(this, EventArgs.Empty);
}
}
将SuppressKeyPress属性从KeyEventArgs设置为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);
}
}
您始终可以在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);
}
}
单击
按钮1的作用是什么?您需要使用e.Handled=true代码>这里!!你是在赢的形式或WPF?e处理没有工作。使用SuppressKeyPress,如Raluca所说。与其调用按钮1单击(此,EventArgs.Empty)
,为什么不使用按钮1.PerformClick()
?请注意,仍有人可能会将T和M粘贴到文本框中。按钮1单击的作用是什么?您需要使用e.Handled=true代码>这里!!你是在赢的形式或WPF?e处理没有工作。使用SuppressKeyPress,如Raluca所说。与其调用按钮1单击(此,EventArgs.Empty)
,为什么不使用按钮1.PerformClick()
?注意,可能仍有人会将T和M粘贴到文本框中。这对于检查数字是否正确非常有用。Raluca在SuppressKey上提供了第一个答案,因此这将作为我的答案,在检查数字时非常有用。Raluca在SuppressKey上提供了第一个答案,因此这将作为我的答案