WinForm 中的输入处理
-
08-07-2019 - |
题
阻止在文本框中使用某些输入键而不阻止特殊击键(例如 Ctrl-V/Ctrl-C)的最佳方法是什么?
例如,只允许用户输入字符或数字的子集,例如 A 或 B 或 C,而不允许输入其他内容。
解决方案
如果不允许密钥,我会使用keydown事件并使用e.cancel来停止密钥。如果我想在多个地方执行此操作,那么我将创建一个继承文本框的用户控件,然后添加一个属性AllowedChars或DisallowedChars来处理它。我有几个变种,我不时使用,有些允许货币格式和输入,有些用于时间编辑等等。
作为用户控件执行此操作的好处是,您可以添加到它并将其设置为您自己的杀手文本框。 ;)
其他提示
这就是我经常处理的方式。
Regex regex = new Regex("[0-9]|\b");
e.Handled = !(regex.IsMatch(e.KeyChar.ToString()));
这只会允许数字字符和退格。问题是在这种情况下您将不被允许使用控制键。如果你想保留这个功能,我会创建自己的文本框类。
我发现唯一有效的解决方案是对 ProcessCmdKey 中的 Ctrl-V、Ctrl-C、Delete 或 Backspace 按键进行预检查,如果它不是 KeyPress 事件中的这些按键之一,则进行进一步验证通过使用正则表达式。
这可能不是最好的方法,但它在我的情况下有效。
protected override bool ProcessCmdKey(ref Message msg, Keys keyData)
{
// check the key to see if it should be handled in the OnKeyPress method
// the reasons for doing this check here is:
// 1. The KeyDown event sees certain keypresses differently, e.g NumKeypad 1 is seen as a lowercase A
// 2. The KeyPress event cannot see Modifer keys so cannot see Ctrl-C,Ctrl-V etc.
// The functionality of the ProcessCmdKey has not changed, it is simply doing a precheck before the
// KeyPress event runs
switch (keyData)
{
case Keys.V | Keys.Control :
case Keys.C | Keys.Control :
case Keys.X | Keys.Control :
case Keys.Back :
case Keys.Delete :
this._handleKey = true;
break;
default:
this._handleKey = false;
break;
}
return base.ProcessCmdKey(ref msg, keyData);
}
protected override void OnKeyPress(KeyPressEventArgs e)
{
if (String.IsNullOrEmpty(this._ValidCharExpression))
{
this._handleKey = true;
}
else if (!this._handleKey)
{
// this is the final check to see if the key should be handled
// checks the key code against a validation expression and handles the key if it matches
// the expression should be in the form of a Regular Expression character class
// e.g. [0-9\.\-] would allow decimal numbers and negative, this does not enforce order, just a set of valid characters
// [A-Za-z0-9\-_\@\.] would be all the valid characters for an email
this._handleKey = Regex.Match(e.KeyChar.ToString(), this._ValidCharExpression).Success;
}
if (this._handleKey)
{
base.OnKeyPress(e);
this._handleKey = false;
}
else
{
e.Handled = true;
}
}
您可以将TextChanged事件用于文本框。
private void txtInput_TextChanged(object sender, EventArgs e)
{
if (txtInput.Text.ToUpper() == "A" || txtInput.Text.ToUpper() == "B")
{
//invalid entry logic here
}
}
不隶属于 StackOverflow