问题
How to filter non-letter keys from the virtual keyboard?
The following method works just for latin alphabet, for unfortune:
public static bool IsLetter(int val) {
return InRange(val, 65, 90) || InRange(val, 97, 122) || InRange(val, 192, 687) || InRange(val, 900, 1159) ||
InRange(val, 1162, 1315) || InRange(val, 1329, 1366) || InRange(val, 1377, 1415) ||
InRange(val, 1425, 1610);
}
public static bool InRange(int value, int min, int max) {
return (value <= max) & (value >= min);
}
回答1:
I think you can use Regex for this, fired in KeyUp event of your TextBox - when user releases key, the method will check if what he pressed fits your requirements. It can look for example like this:
myTextbox.KeyUp += myTextbox_KeyUp; // somewhere in Page Constructor
private void myTextbox_KeyUp(object sender, System.Windows.Input.KeyEventArgs e)
{
Regex myReg = new Regex(@"\d");
if (myReg.IsMatch(e.Key.ToString()) || e.Key == Key.Unknown)
{
string text = myTextbox.Text;
myTextbox.Text = text.Remove(text.Length - 1);
myTextbox.SelectionStart = text.Length;
}
}
The code above checks for any digit pressed or Unknown key (debug to see which are they) - if the user pressed digit, then the last entered char is removed form text. You can also define your Regex differently for example allowing only letters:
Regex myReg = new Regex(@"^[a-zA-Z]+$");
if (!myReg.IsMatch(e.Key.ToString()) || e.Key == Key.Unknown)
{ // the same as above }
I assume that you have already set the scope of your keyboard.
EDIT - non latin keyboard
The code above wouldn't grant success if you use for example cyrillic, then e.Key will be Key.Unknown which causes a little problem. But I've managed to handle this task with checking the last character entered if it is nonAlphaNumeric \W
or digit \d
, delete it- works quite fine even with strange chars:
private void myTextbox_KeyUp(object sender, System.Windows.Input.KeyEventArgs e)
{
string added = myTextbox.Text.ElementAt(myTextbox.Text.Length - 1).ToString();
Regex myReg = new Regex(@"[\W\d]");
if (myReg.IsMatch(added))
{
string text = myTextbox.Text;
myTextbox.Text = text.Remove(text.Length - 1);
myTextbox.SelectionStart = text.Length;
}
}
来源:https://stackoverflow.com/questions/21191261/allowing-only-letters-for-input