您的位置:首页 > 其它

在windows from 中怎样限制一个文本框只能输入数字(0-9)

2004-11-10 23:46 866 查看
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);
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: