更新时间:2023-02-21 11:54:57
正如评论中提到的(以及我输入的另一个答案),您需要注册一个事件处理程序来捕获文本框上的 keydown 或 keypress 事件.这是因为 TextChanged 仅在 TextBox 失去焦点时触发
As mentioned in a comment (and another answer as I typed) you need to register an event handler to catch the keydown or keypress event on a text box. This is because TextChanged is only fired when the TextBox loses focus
下面的正则表达式可以让你匹配那些你想要允许的字符
The below regex lets you match those characters you want to allow
Regex regex = new Regex(@"[0-9+-/*()]");
MatchCollection matches = regex.Matches(textValue);
而这恰恰相反,会捕获不允许的字符
and this does the opposite and catches characters that aren't allowed
Regex regex = new Regex(@"[^0-9^+^-^/^*^(^)]");
MatchCollection matches = regex.Matches(textValue);
我不会假设会有一个匹配项,因为有人可以将文本粘贴到文本框中.在这种情况下捕获 textchanged
I'm not assuming there'll be a single match as someone could paste text into the textbox. in which case catch textchanged
textBox1.TextChanged += new TextChangedEventHandler(textBox1_TextChanged);
private void textBox1_TextChanged(object sender, EventArgs e)
{
Regex regex = new Regex(@"[^0-9^+^-^/^*^(^)]");
MatchCollection matches = regex.Matches(textBox1.Text);
if (matches.Count > 0) {
//tell the user
}
}
并验证单个按键
textBox1.KeyPress += new KeyPressEventHandler(textBox1_KeyPress);
private void textBox1_KeyPress(object sender, System.Windows.Forms.KeyPressEventArgs e)
{
// Check for a naughty character in the KeyDown event.
if (System.Text.RegularExpressions.Regex.IsMatch(e.KeyChar.ToString(), @"[^0-9^+^-^/^*^(^)]"))
{
// Stop the character from being entered into the control since it is illegal.
e.Handled = true;
}
}