Public Class NumericTextBox
Inherits System.Windows.Forms.TextBox
Private Sub NumericTextBox_KeyPress(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles MyBase.KeyPress '拦截KeyPress消息
'{
'判断输入的是否是数字,如果不是数字则返回
If (Not Char.IsDigit(e.KeyChar)) Then
'{
e.Handled = True '如果输入不是数字, 则向系统声明KeyPress事件已经处理,忽略
'系统对KeyPress事件的继续处理
'}
Else
'{
e.Handled = False '如果输入是数字,则继续让系统处理KeyPress消息以显示字符
'}
End If
'}
End Sub
End Class
你用这个类代替你的Form中的System.Form.TextBoxTextBox类就可以了; 原理是从System.Windows.Forms.TextBox自己派生一个类,然后拦截它的KeyPress事件;当判断
用户按下的是非数字键, 则简单的就向系统报告KeyPress已经被处理;如果是数字键,
则放行让系统处理.
OR
先处理keypreee事件
If Not (IsNumeric(e.KeyChar) Or e.KeyChar = ChrW(8) Or e.KeyChar = ChrW(46)) Then
e.Handled = True
End If
再就是复制粘贴事件
[DllImport("user32.dll", CharSet=CharSet.Auto)] public static extern int GetWindowLong(HandleRef hWnd, int nIndex);
[DllImport("user32.dll", CharSet=CharSet.Auto)] public static extern int SetWindowLong(HandleRef hWnd, int nIndex, int dwNewLong);
public const int GWL_STYLE = -16;
public const int ES_NUMBER = 0x2000;
public static void TextBoxNumberOnly(TextBox textBox, bool readOnly)
{
int style = GetWindowLong(new HandleRef(textBox, textBox.Handle), GWL_STYLE);
if(readOnly)
style |= ES_NUMBER;
else
style &= ~ES_NUMBER;
SetWindowLong(new HandleRef(textBox, textBox.Handle), GWL_STYLE, style);
}