By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
435,028 Members | 1,825 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 435,028 IT Pros & Developers. It's quick & easy.

A simple numeric only textbox

P: n/a
This is a simple example of a numeric only text box. It allows only the
entry of integer values. The advantage of this example is that it also
handles user attempts to past non integer text data into the text box...

Option Strict On
Option Explicit On

Imports System
Imports System.Windows.Forms
Imports System.ComponentModel
Imports System.Text.RegularExpressions
Imports System.Runtime.InteropServices

Public Class NumericTextBox
Inherits System.Windows.Forms.TextBox

Private Const ES_NUMBER As Integer = &H2000
Private Const CF_TEXT As Integer = 1
Private Const WM_PASTE As Integer = &H302
Private regEx As regEx

Public Sub New()
Me.regEx = New Regex("\D", RegexOptions.Compiled)
End Sub
Protected Overrides ReadOnly Property CreateParams() As
System.Windows.Forms.CreateParams
Get
Dim cp As CreateParams = MyBase.CreateParams
cp.Style = cp.Style Or ES_NUMBER
Return cp
End Get
End Property

Protected Overrides Sub WndProc(ByRef m As
System.Windows.Forms.Message)
Select Case m.Msg
Case WM_PASTE
If IsClipboardFormatAvailable(CF_TEXT) Then
If OpenClipboard(IntPtr.Zero) Then
Dim hMem As IntPtr = GetClipboardData(CF_TEXT)
Dim hData As IntPtr = GlobalLock(hMem)

Dim data As String =
Marshal.PtrToStringAnsi(hData)
GlobalUnlock(hMem)
CloseClipboard()

If regEx.Match(data).Success Then
m.Result = IntPtr.Zero
Else
MyBase.WndProc(m)
End If
End If
Else
MyBase.WndProc(m)
End If
Case Else
MyBase.WndProc(m)
End Select
End Sub

<DllImport("user32", SetLastError:=True)> _
Private Shared Function OpenClipboard(ByVal hWndNewOwner As IntPtr)
As Boolean
End Function

<DllImport("user32", SetLastError:=True)> _
Private Shared Function IsClipboardFormatAvailable(ByVal format As
Integer) As Boolean
End Function

<DllImport("user32", SetLastError:=True)> _
Private Shared Function GetClipboardData(ByVal format As Integer) As
IntPtr
End Function

<DllImport("user32", SetLastError:=True)> _
Private Shared Function CloseClipboard() As Boolean
End Function

<DllImport("kernel32", SetLastError:=True)> _
Private Shared Function GlobalLock(ByVal hMem As IntPtr) As IntPtr
End Function

<DllImport("kernel32", SetLastError:=True)> _
Private Shared Function GlobalUnlock(ByVal hMem As IntPtr) As
Boolean
End Function

End Class

I orginally wrote this in C#, but I converted it to VB.NET for posting
here :)
--
Tom Shelton [MVP]
OS Name: Microsoft Windows XP Professional
OS Version: 5.1.2600 Service Pack 2 Build 2600
System Up Time: 26 Days, 23 Hours, 43 Minutes, 47 Seconds
Nov 21 '05 #1
Share this question for a faster answer!
Share on Google+

This discussion thread is closed

Replies have been disabled for this discussion.