我希望TextBox只使用KeyDown事件接受某些特定字符。我已经有了它的工作,除了一个字符,单引号。为了得到将要写的字符,我使用(char)e.KeyValue
,它适用于除引号之外的所有字符(它给出Û)。我知道我可以使用e.KeyCode
,但它的值是Keys.Oem4
,AFAIK可能在不同系统中有所不同。
有没有办法始终如一地检测单引号按键?
代码段:
char c = (char)e.KeyValue;
char[] moves = { 'r', 'u', ..., '\'' };
if (!(moves.Contains(c) || e.KeyCode == Keys.Back || e.KeyCode == Keys.Space))
{
e.SuppressKeyPress = true;
}
答案 0 :(得分:1)
我已经使用了很长时间了。它处理单引号就好了。 e.KeyChar == 39'\''和e.Handled = true表现完全符合您的预期。我用KeyPress事件对它进行了测试,并在那里工作。
protected override void OnKeyPress(KeyPressEventArgs e)
{
base.OnKeyPress(e);
if (e.KeyChar == (char)8) // backspace
return;
if (e.KeyChar == (char)3) // ctrl + c
return;
if (e.KeyChar == (char)22) // ctrl + v
return;
typedkey = true;
if (_allowedCharacters.Count > 0) // if the string of allowed characters is not empty, skip test if empty
{
if (!_allowedCharacters.Contains(e.KeyChar)) // if the new character is not in allowed set,
{
e.Handled = true; // ignoring it
return;
}
}
if (_disallowedCharacters.Count > 0) // if the string of allowed characters is not empty, skip test if empty
{
if (_disallowedCharacters.Contains(e.KeyChar)) // if the new character is in disallowed set,
{
e.Handled = true; // ignoring it
return;
}
}
}
答案 1 :(得分:-1)
正如@EdPlunkett建议的那样,this answer对我有用:
$group