ActiveX Control Tutorial - Part 2
Today, we're going to start creating an advanced text box.
In just a few clicks of the mouse, we'll allow users of our control to dictate how the text box works. Perhaps it will restrict people to entering just numbers or mere text. This will be done by setting properties.
We'll also make the text box automatically translate characters to upper case, lower case — or any ol' case.
So let's get going...
- Start up Visual Basic
- Create a new 'ActiveX Control' project
- Add a text box to your workspace
For the moment, don't worry about sizing or positioning or whatever. These things do matter — just ask my girlfriend but we'll deal with them later.
- Rename the text box to 'txtTextBox'
- Remove 'Text1' from the Text property
We haven't really done much yet, but let's test it so far.
- Click File, Add Project
- Select 'Standard EXE'
- Add your 'UserControl1' control from the toolbox direct onto Form1
Your screen should look a little something like this:
Notice how the text box inside our control doesn't automatically resize itself?
- Right click on 'Project2' in the Project Explorer and click Remove Project, not saving any changes
The text box doesn't automatically resize because as of yet, we haven't told it to. Oh, and 'cause Visual Basic is about as smart as the winner of last year's "World's Scruffiest Bloke" competition.
- Click View, Code to enter the code window
- Select UserControl from the Object drop-down box
Don't forget that the UserControl is just your control. When something happens to it, certain events fire — such as Initialize, Resize, LostFocus and so on. It's the equivalent of the Form object in regular programming, where you have events such as Load and Unload.
- Select Resize from the Procedure drop-down box
- Add the following code to your project:
Private Sub UserControl_Resize() With txtTextBox .Height = UserControl.ScaleHeight .Top = UserControl.ScaleTop .Left = UserControl.ScaleLeft .Width = UserControl.ScaleWidth End WithEnd Sub
Here, we're resizing the dimensions of the text box depending on various properties of the UserControl object.
The UserControl object is there to tell you how your user is playing with the control. So if they resize it, the Resize event fires and you grab the new ScaleHeight, etc. properties, reorganising your controls as such.
In our project, we simply set the text box properties equal to the exact UserControl Scale properties. Of course, if you had more than just one simple text box to resize, you'd have to start with a few Einstein-like calculations. For now, I'll spare you the pleasure.
Go ahead and test the control— just as we did earlier.
See what happens? Whenever the user resizes your control, the text box follows!
My test project looks like this:
Sure, it's about as stunning as Queen Elizabeth's bottom, but this is only the second tutorial...
Page 2 of 6