65.9K
CodeProject 正在变化。 阅读更多。
Home

在 TextBox 中只允许数字输入

2023年5月7日

CPOL
viewsIcon

6260

如何只允许 TextBox 输入数字

你可能见过一个 Windows 文本框,它会禁止非数字输入,并显示类似以下截图的错误消息

这可以通过 .NET 轻松实现,只需将 ES_NUMBER 样式应用于 文本框

Public Sub SetNumericInputMode(ByVal txtBox As TextBox)
    Dim style As Int32 = GetWindowLong(txtBox.Handle, GWL_STYLE)
    SetWindowLong(txtBox.Handle, GWL_STYLE, style Or ES_NUMBER)
End Sub

当然,SetWindowLong 必须正确声明

<DllImport(“user32.dll”)>
Private Shared Function SetWindowLong( _
     ByVal hWnd As IntPtr, _
     ByVal nIndex As Integer, _
     ByVal dwNewLong As IntPtr) As Integer
End Function

现在,如果你使用的是 Telerik RadControls for WinForms 中的 RadTextBox 控件呢? 以下代码适用于普通的 文本框,可以编译,但对 RadTextBox 无效

SetNumericInputMode(textBox1.Handle);

原因是 RadTextBox 只是本机 Win32 文本框 的容器。 任何样式更改都必须直接应用于实际的 文本框,而不是容器。 以下代码将有效

Public Sub SetNumericInputMode(ByVal txtBox As RadTextBox)
  'special handling for RadTextbox as the actual Win32 textbox is hidden underneath
  Dim hwnd As IntPtr = CType(txtBox.TextBoxElement.Children(0), _
                             RadTextBoxItem).HostedControl.Handle
  Dim style As Int32 = GetWindowLong(hwnd, GWL_STYLE)
  SetWindowLong(hwnd, GWL_STYLE, style Or ES_NUMBER)
End Sub

请注意,ES_NUMBER 仅阻止用户在 文本框 中输入非数字 (0..9) 输入。 它不会阻止用户粘贴随机文本。 对于更高级的功能,我建议使用 MaskedTextBox

© . All rights reserved.