我目前正在开发一个WPF应用程序,我想拥有一个TextBox只能包含数字条目的应用程序.我知道当我丢失焦点并阻止内容为数字时我可以验证它的内容,但在其他Windows窗体应用程序中,我们使用完全阻止除了数字之外的任何输入被写下来.另外,我们使用这个代码放在一个单独的dll中,以便在很多地方引用它.
以下是2008年不使用WPF的代码:
Public Shared Sub BloquerInt(ByRef e As System.Windows.Forms.KeyPressEventArgs, ByRef oTxt As Windows.Forms.TextBox, ByVal intlongueur As Integer)
Dim intLongueurSelect As Integer = oTxt.SelectionLength
Dim intPosCurseur As Integer = oTxt.SelectionStart
Dim strValeurTxtBox As String = oTxt.Text.Substring(0, intPosCurseur) & oTxt.Text.Substring(intPosCurseur + intLongueurSelect, oTxt.Text.Length - intPosCurseur - intLongueurSelect)
If IsNumeric(e.KeyChar) OrElse _
Microsoft.VisualBasic.Asc(e.KeyChar) = System.Windows.Forms.Keys.Back Then
If Microsoft.VisualBasic.AscW(e.KeyChar) = System.Windows.Forms.Keys.Back Then
e.Handled = False
ElseIf strValeurTxtBox.Length < intlongueur Then
e.Handled = False
Else
e.Handled = True
End If
Else
e.Handled = …Run Code Online (Sandbox Code Playgroud)