AllAPI Network - The KPD-Team

 
Allapi Network
 API-Guide
 ApiViewer

 API List

 
API Resources
 Tips & Tricks
 VB Tutorials
 Error Lookup
 
Misc Stuff
 VB examples
 VB Tools
 VB Links
 Top Downloads
 
This Site
 Search Engine
 Contact Form
 

Donate to AllAPI.net

Using WithEvents to add features to a textbox

Have you ever felt that certain standard Windows controls were lacking features? Would you like to add features to a textbox which you wouldn't have to code every time you created a new textbox? Typically, you would create a generic subroutine and call it from the event of every control.  With VB5 and higher, a command named "WihEvents" provides a simpler solution.  Let's say you wanted a textbox that would only accept uppercase letters as input. If lowercase letters were entered they would be automatically converted to uppercase. Numbers and all symbols would be rejected.   And whenever the mouse pointer passed over it, you wanted to show the mouse position in the textbox. Finally, let's say you didn't want the fourth textbox to accept the letter 'Z'.

Create a standard EXE project, add four textbox controls onto the default form, and add a class module. Enter the following code to Form1:

'General Declarations
Private clsTextBox1 As Class1
Private clsTextBox2 As Class1
Private clsTextBox3 As Class1
Private clsTextBox4 As Class1

Private Sub Form_Load()
Set clsTextBox1 = New Class1
Set clsTextBox1.TextBoxCtl = Text1
Set clsTextBox2 = New Class1
Set clsTextBox2.TextBoxCtl = Text2
Set clsTextBox3 = New Class1
Set clsTextBox3.TextBoxCtl = Text3
Set clsTextBox4 = New Class1
Set clsTextBox4.TextBoxCtl = Text4
End Sub

Private Sub Text4_KeyPress(KeyAscii As Integer)
'-- This code executes before the class keypress
If KeyAscii = Asc("a") Then Beep
End Sub

In Class1, enter the following code:

Private WithEvents txt As TextBox
Public Property Set TextBoxCtl(OutsideTextBox As TextBox)
Set txt = OutsideTextBox
End Property

Private Sub txt_KeyPress(KeyAscii As Integer)
'-- Convert to Uppercase
KeyAscii = Asc(UCase$(Chr$(KeyAscii)))
End Sub

Private Sub txt_MouseMove(Button As Integer, Shift As Integer, _
X As Single, Y As Single)
txt.ToolTipText = "X:" & X & " Y:" & Y
End Sub

To add new functionality to all four textboxes, simply enter code into the class.   Remember, the keypress event for textbox4 executes first when a key is pressed. Then, the Classes keypress event fires next.

 

 


Copyright © 1998-2007, The Mentalis.org Team - Privacy statement
Did you find a bug on this page? Tell us!
This site is located at http://allapi.mentalis.org/