以下代码适用于winforms
Dim allowedChars as String = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz "
If allowedChars.IndexOf(e.KeyChar) = -1
If Not e.KeyChar = Chr(Keys.Back) Then
e.Handled = True
Beep()
End If
End If
但是在WPF中我不知道如何实现上面的代码?
答案 0 :(得分:4)
以下是C#,但您可以轻松将其转换为VB.NET。
private void NumericTextBox_PreviewKeyDown(object sender, KeyEventArgs e)
{
char c = (char)KeyInterop.VirtualKeyFromKey(e.Key);
if ("ABCDEF".IndexOf(c) < 0)
{
e.Handled = true;
MessageBox.Show("Invalid character.");
}
}
您可能需要导入System.Windows.Input
才能获得KeyInterop
。上面的代码段进入TextBox的PreviewKeyDown
事件。
以上所有内容均可见here
答案 1 :(得分:1)
在C#中
private bool ValidChar(string _char)
{
string Lista = @" ! "" # $ % & ' ( ) * + , - . / 0 1 2 3 4 5 6 7 8 9 : ; < = > ? @ A B C D E F G H I J K L M N O P Q R S T U V W X Y Z ";
return Lista.IndexOf(_char.ToUpper()) != -1;
}
private void textBoxDescripcion_PreviewTextInput(object sender, TextCompositionEventArgs e)
{
if (!ValidChar(e.Text))
e.Handled = true;
}
在vb
Private Function ValidChar(_char As String) As Boolean
Dim Lista As String = " ! "" # $ % & ' ( ) * + , - . / 0 1 2 3 4 5 6 7 8 9 : ; < = > ? @ A B C D E F G H I J K L M N O P Q R S T U V W X Y Z "
Return Lista.IndexOf(_char.ToUpper()) <> -1
End Function
Private Sub textBoxDescripcion_PreviewTextInput(sender As Object, e As TextCompositionEventArgs)
If Not ValidChar(e.Text) Then
e.Handled = True
End If
End Sub