如何在不阻止特殊按键(如 Ctrl-V/Ctrl-C)的情况下,最好地阻止文本框中使用某些输入键?
例如,只允许用户输入字符或数字子集,如 A 或 B 或 C,而不允许其他任何字符。
如何在不阻止特殊按键(如 Ctrl-V/Ctrl-C)的情况下,最好地阻止文本框中使用某些输入键?
例如,只允许用户输入字符或数字子集,如 A 或 B 或 C,而不允许其他任何字符。
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;
}
}
private void txtInput_TextChanged(object sender, EventArgs e)
{
if (txtInput.Text.ToUpper() == "A" || txtInput.Text.ToUpper() == "B")
{
//invalid entry logic here
}
}