文本框中只能输入数字

1 同上上篇日志  老师给的代码

Private Sub TextBox1_KeyPress(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles TextBox1.KeyPress
        Dim c As Char
        c = e.KeyChar
        If c = "."c Then
            If InStr(TextBox1.Text, e.KeyChar) > 0 Or (InStr(TextBox1.Text, "-") > 0) And (TextBox1.SelectionStart = 0) Then
                e.KeyChar = ""
            End If
        ElseIf c = "-"c Then
            If InStr(TextBox1.Text, c) > 0 Or TextBox1.SelectionStart > 0 Then
                e.KeyChar = ""
            End If
        ElseIf c = "0"c Then
            If (TextBox1.SelectionStart = 0 And Not TextBox1.Text.StartsWith("0") And TextBox1.Text.Length <> 0) Or (TextBox1.SelectionStart <= 1 And TextBox1.Text.StartsWith("0")) Then
                e.KeyChar = ""
            End If
        ElseIf c = ControlChars.Back Then
        ElseIf InStr("123456789", e.KeyChar) <= 0 Then
            e.KeyChar = ""
        End If
    End Sub

 

说实话看的不是太懂=_+

e.KeyValue、e.KeyChar 都可以获得键盘的输入值,请问两种在用法和功能上有什么区别?
KeyChar是在keyPressEvent里面获得的char类型返回值,
KeyValue取得KeyDown 或KeyUp事件的键盘值,返回的整形。
InStr
返回一个整数,该整数指定一个字符串在另一个字符串中的第一个匹配项的起始位置。
String2 位于 String1 ---------------匹配开始的位置
TextBoxBase.SelectionStart 属性
获取或设置文本框中选定的文本起始点。

 

2. 控制键盘只能输入数字//未验证

private   void   textBox3_KeyPress(object sender,System.Windows.Forms.KeyPressEventArgs e) 
{ 
//阻止从键盘输入键 
e.Handled = true; 
if(e.KeyChar> =48 && e.KeyChar<=57) 
  { 
   e.Handled  = false; 
  } 
} 

 

 

3.参考网页:http://hi.baidu.com/pepsisoft/blog/item/d8664327bb011c03908f9d2c.html  //这个我看懂了=_+

Private Sub TextBox1_KeyPress(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles Textbox1.KeyPress
    If Char.IsDigit(e.KeyChar) Or e.KeyChar = "." Or e.KeyChar = Chr(8) Then
        If e.KeyChar = "." And InStr(TextBox1.Text, ".") > 0 Then
            e.Handled = True
         Else
             e.Handled = False
         End If
     ElseIf e.KeyChar = "-" And TextBox1.Text = "" Then
         e.Handled = False
     Else
         e.Handled = True
     End If
End Sub

 

====================

 

另有一帖子是搜keychar搜到的,关于Datagrid键盘事件响应。

http://www.newasp.net/tech/net/10081.html

你可能感兴趣的:(C++,c,windows,.net,C#)