ActiveX Control Tutorial - Part 1, Page 4
Now, brace yourself as we prepare to create our own ActiveX control.
We're going to create a little option button that flashes a few times when you run a certain method. It's not overly useful, but could help grab a user's attention.
- Start Visual Basic
- Create a New 'ActiveX Control' project
A grey box should appear on your screen. This is your workspace — it's basically a form without a border, caption or minimize/maximise/close buttons.
And that makes sense, after all when did you last use a control that has its own close button?
First off, let's rename our ActiveX control:
- Change the Name property of UserControl1 to 'Flasher'
- Now change the Name property of Project1 to 'Animation'
- Double-click on the Option Button control in the toolbox
- Remove the Caption property of the Option Button
- Change its Name property to 'optFlasher'
We've just added an Option Button to the workspace. Now let's add the Timer control:
- Double-click on the Timer control
- Change its Name property to 'tmrAnimation'
That's great. Now I want you to resize a few of the things on your screen. We'll be doing all this resizing in code later on, but for now:
- Move the Option Button to the very top left, so it just touches the corner edges of your workspace like this:
- Now resize the workspace so it just touches the bottom edges of your Option Button like this:
Now the stuff you currently see in your workspace will become your 'control', the thing your user sees when adding it to their forms.
Hmm, it's about time we added some code. Not much, just a lil'.
- Enter the code window by selecting View, Code
- Type in the following code:
Public Sub Flash() tmrAnimation.Interval = 300 End Sub
This just sets the Interval property of tmrAnimation to around a third-of-a-second (300 milliseconds). When the Timer springs into action every 300-milliseconds, it fires its Timer event.
So let's add code to that...
- In the Object drop-down list (which currently says General), select 'tmrAnimation'
- The Procedure drop-down list next to it should say 'Timer' — if not, select the 'Timer' event from the list
Your screen should look a little like this at the moment:
- Tap in the following code:
Static NoOfFlashes As Integer ' This is just a variable that holds ' a number - the 'Static' prefix just ' means it doesn't forget its value ' when this procedure is over... optFlasher.Value = Not (optFlasher.Value) ' Sets the value of our Option Button ' to the opposite of its current value... ' so if it's "on", it'll be turned off - ' and vice versa NoOfFlashes = NoOfFlashes + 1 ' Increment the variable to show number ' of times we have "flashed" If NoOfFlashes = 8 Then ' If we've had eight separate flashes so far NoOfFlashes = 0 ' Reset the NoOfFlashes... tmrAnimation.Interval = 0 ' ... and turn off the timer End If
That's it! You've completed the creation of your first ActiveX control.
Now let's put it to the test...
Page 4 of 6