VB TIP: 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 SubPrivate 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 PropertyPrivate Sub txt_KeyPress( _ KeyAscii As Integer) '-- Convert to Uppercase KeyAscii = Asc(UCase$(Chr$(KeyAscii))) End SubPrivate 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.