VB.NET设计只能输入数字的文本框

代码如下:

 1 Public Class NumericTextBox
 2   Inherits System.Windows.Forms.TextBox
 3 
 4 #Region " Windows Form Designer generated code "
 5 
 6   Public Sub New()
 7     MyBase.New()
 8 
 9     'This call is required by the Windows Form Designer.
10     InitializeComponent()
11 
12     'Add any initialization after the InitializeComponent() call
13 
14   End Sub
15 
16   'UserControl1 overrides dispose to clean up the component list.
17   Protected Overloads Overrides Sub Dispose(ByVal disposing As Boolean)
18     If disposing Then
19       If Not (components Is Nothing) Then
20         components.Dispose()
21       End If
22     End If
23     MyBase.Dispose(disposing)
24   End Sub
25 
26   'Required by the Windows Form Designer
27   Private components As System.ComponentModel.IContainer
28 
29   'NOTE: The following procedure is required by the Windows Form Designer
30   'It can be modified using the Windows Form Designer.  
31   'Do not modify it using the code editor.
32   <System.Diagnostics.DebuggerStepThrough()> Private Sub InitializeComponent()
33     components = New System.ComponentModel.Container()
34   End Sub
35 
36 #End Region
37 
38   Private Sub NumericTextBox_KeyPress(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles MyBase.KeyPress
39     Dim KeyAscii As Integer
40     KeyAscii = Asc(e.KeyChar)
41 
42     Select Case KeyAscii
43 
44       Case 48 To 57, 8, 13      ' these are the digits 0-9, backspace, 
45         ' and carriage return
46         ' we're OK on these, don't do anything
47 
48       Case 45                   ' minus sign
49 
50         ' The number can only have one minus sign, so 
51         ' if we already have one, throw this one away
52         If InStr(Me.Text, "-") <> 0 Then
53           KeyAscii = 0
54         End If
55 
56         ' if the insertion point is not sitting at zero
57         ' (which is the beginning of the field), throw away the minus
58         ' sign (because it's not valid except in first position)
59         If Me.SelectionStart <> 0 Then
60           KeyAscii = 0
61         End If
62 
63       Case 46                   ' this is a period (decimal point)
64 
65         ' if we already have a period, throw it away
66         If InStr(Me.Text, ".") <> 0 Then
67           KeyAscii = 0
68         End If
69 
70       Case Else
71         ' provide no handling for the other keys
72         KeyAscii = 0
73 
74     End Select
75 
76     ' If we want to throw the keystroke away, then set the event
77     ' as already handled. Otherwise, let the keystroke be handled normally.
78     If KeyAscii = 0 Then
79       e.Handled = True
80     Else
81       e.Handled = False
82     End If
83 
84   End Sub
85 End Class