Вы находитесь на странице: 1из 8

Simple Steps in VB.NET.

Building a Custom Control Page 1 of 8

DevCity.NET - http://www.devcity.net

Simple Steps in VB.NET. Building a Custom Control


http://www.devcity.net/Articles/87/1/ssteps_customcontrol.aspx
by Ged Mead
Published on 5/14/2003
Ged Mead
In this article in the 'Simple Steps in VB.Net' series vbCity Leader XTab
shows you how to create a simple custom control. You are taken through Ged Mead
the procedures needed to enhance the functionality of the VB.Net standard (XTab) has
Button control by incorporating features which will make your button more been
eye-catching. The article shows you how to create the user control by around
adding customised properties and events. The attached solution includes computers
additional enhancements not covered in the step by step guide and also since the
demonstrates how you can take the basic idea much further. 1980's
when the first affordable
Simple Steps in VB.NET. Building a Custom Control home computers came on
the market. His journey from
that very first Dragon 32 to
Article source code: ssteps_customcontrol.zip the present has taken him
through many different
facets of the IT Industry.
Introduction These include formal training
as a Systems Analyst,
This article is for beginners and demonstrates step by step how you can employment in a mainframe
create a very basic custom control. software development
environment, and a short
The control we are going to create is an enhanced version of a standard time spent demonstrating
Button control which we will call the XtraButton control. rugged military IT systems in
the days when it took two
strong men to carry a
In this demo we are simply going to simply build on the functionality of an
'mobile' system.
existing control, a Button control. There are much more sophisticated
things that can be done, but as this is a 'Simple Steps' article, we'll stick to
basics for now. We'll maybe get more adventurous in a later article. His most rewarding
challenge was the creation of
a financial management
Setting Up system for a large
organisation.
First of all, open a new Project. Select the 'Windows Control Library' icon
from the New Project - Templates Window. Now based in an idyllic
lochside location in the West
Give the Project a meaningful name - "XtraButton" will do nicely. of Scotland, he is currently
involved in a range of
development projects,
Accept or overwrite the location for the files to be saved to. whenever he can drag his
gaze away from the stunning
surrounding views, that is!

Ged is a Microsoft MVP,


Senior Editor for
DevCity.NET, vbCity
Developer Community
Leader and Admin, Helper of
the Month competition
winner and DevCity.NET
newsletter Editor.

http://www.devcity.net/PrintArticle.aspx?ArticleID=87 6/24/2008
Simple Steps in VB.NET. Building a Custom Control Page 2 of 8

Press OK. This will create a Solution which contains a Project named
XtraButton, which in turn contains an object named UserControl1.vb.

Let's change the name of this user control to something more meaningful -
"XtraButton" again.

Highlight the name 'UserControl1.vb' in the Solution Explorer and change it


to XtraButton.vb.

We also need to rename the Class itself. So open the XtraButton.vb's code
window and change the line which reads:

Public Class UserControl1

So that it reads:

Public Class XtraButton

As we are basing our new control totally on the standard button control, we
can also change the code so that it specifically inherits all the properties,
methods and events of a button.

Still in the Code Window, change the line that reads:

Inherits System.Windows.Forms.UserControl

So that it reads:

Inherits System.Windows.Forms.Button

Creating a Test Bed


Before we really begin to roll our sleeves up and create our nifty new

http://www.devcity.net/PrintArticle.aspx?ArticleID=87 6/24/2008
Simple Steps in VB.NET. Building a Custom Control Page 3 of 8

control, we ought to have somewhere to test it out. It's often handy to be able to test it at various stages
during it's creation, so we will deal with that requirement now.

In the Solution Explorer, select Solution 'XtraButton' and right-click it. From the drop-down menu, select
Add... , then 'New Project'.

This time, make sure you select a 'Windows Application' template (it will probably still be highlighting the
Windows Control Library template you selected previously). Give this new Windows Application project a
meaningful name - 'Test Form', for instance.

I prefer to save the test projects in a subfolder of the Custom Control's own folder, so if you want to do that
then use the Browse button to navigate your way there and then click OK to save it.

A quick check in the Solution Explorer will reassure you that all is as it should be - two projects are now
displayed: XtraButton and Test Form.

Building the new Button


Turning our attention back to the user control itself now, by changing the code line so that the control inherits
specifically from the Button control class and not from the more generic 'UserControl' we actually already have
a User Control. However, it's not a very exciting one, because it simply replicates the standard button control
at this stage.

But we'll continue to take this a small step at a time. In the Visual Studio menu, choose Build, then Build
XtraButton. You're unlikely to get any errors showing in the Output Window (but if you do, I would suggest
that you're sufficiently unlucky that you should avoid walking under ladders or going outside in lightning
storms!)

(Don't forget to save your Solution at regular intervals.)

Just Checking
Another brief sidestep here to allow us to check that the Control does actually exist and that we can use it, if
we wanted to.

Open the Design Window of Form1 in your Test Form Project (selectable from the Solution Explorer).

You've saved and Built the XTraButton. Now, in the Solution Explorer, select the Test Form project. Right Click
on the project name and from the context menu that appears, select 'Add Reference'. A new dialog box
entitled 'Add Reference' will then appear.

http://www.devcity.net/PrintArticle.aspx?ArticleID=87 6/24/2008
Simple Steps in VB.NET. Building a Custom Control Page 4 of 8

This dialog box has three tabs. Select the 'Projects' tab. It should contain only one entry - 'XtraButton' and its
path information. Make sure this item is highlighted and click on the 'Select' button to the right of the dialog
box. It will then appear in the lower pane. Select this entry to highlight it, then finally click the OK button
down at the bottom of the dialog box to confirm and close it.

Now, open the Toolbox. The Windows Forms Tab will be open by default. Use the small down arrow on the Tab
to scroll to the bottom of the list of available controls. And there at the bottom of the list you should find -
voila ! - the XtraButton control.

If you find that this doesn't work - and it can be problematic sometimes - then the best procedure is this.
Towards the end of this article, there is a paragraph which is titled "Using Your Control in Other Projects".
Follow the instructions in that paragraph, but START FROM WHERE IT SAYS "Right Click on the ToolBox..."
because you obviously don't want to have another project on the go just yet; you still have a bit of legwork to
do here first! This will enable you to add the XtraButton to your toolbox.

Select the XtraButton from the ToolBox and put one instance of it on your form Double click the icon or left
click to select and draw it on the form. (If you were a bit generous with the size of the drawing surface when
you first created the User Control Project, double clicking might present with a larger than life button!)

For the avoidance of any confusion (as if!), I should point out that the XtraButton appears at the end of the
ToolBox list by default. It just happens to be a coincidence that in the example above, it is the last item
because it begins with a letter X. If we'd named it SmartButton it would still have been sitting there last in
line.

Running Before You Can Walk


At this stage (if you're easily excited) you may be keen to try running the solution in the usual way by
pressing F5 or clicking the little Start arrow at the top of the IDE. Go on, then, give it a go!

Disappointing, huh? This little problem arises because at the moment the UserControl project is the StartUp
project for this Solution (you created it first, remember?) . User Control projects don't have a Sub Main and
can't be executed (VS creates a DLL file for you, but we really don't need to get into that).

All you have to do is set the Test Form project as Startup project.

http://www.devcity.net/PrintArticle.aspx?ArticleID=87 6/24/2008
Simple Steps in VB.NET. Building a Custom Control Page 5 of 8

Here's the easy way to do this:

1. Select the Test Form project in Solution Explorer


2. Right click it
3. Choose "Set as Startup Project"

Now try running it again and everything will be fine - not very exciting ... but fine!

If you're interested, you may also check out the Solution Explorer once again and if you look at the
References for the Test Form project, you will see that XtraButton has been added.

Let's Get Coding


Let's get started with those additional properties now. What might be neat would be to add a couple of ways
of highlighting the button. The first way we'll do this is have the button change color when the mouse passes
or hovers over it. And of course, we'll also need to include the code to change it back to the original color
when the mouse is no longer over the button. Depending on the color chosen this can give the impression that
the button 'lights up' as the mouse passes over it.

We need to declare some variables to hold the values of the button's colors as they change.

Add this code to the XtraButton Class's code in the Code Window:

Private mOldColor As Color ' Original button color


Private mMOColor As Color ' Mouse Over color

We can now incorporate these private variables into a new Property - the MouseOverColor Property. OK, so
it's a bit long as names go, but it is descriptive!

Here is the code to create that property:

Property MouseOverColor() As Color


Get
MouseOverColor = mMOColor
End Get
Set(ByVal Value As Color)
mMOColor = Value
End Set
End Property

Once the control has been built, this new property will appear in the Properties Window of any instance of the
XtraButton control that is placed on a form. And just like other standard properties, it can be changed at
designtime in the Properties Window or at runtime as a result of code and/or user actions.

OK, fine, but so far it won't actually do anything, will it? So let's address that right now.

We'll create a procedure that will be called automatically whenever the mouse enters the visible area of the
button. Here is that code:

Private Sub XB_MouseEnter(ByVal sender As Object, _


ByVal e As System.EventArgs) Handles MyBase.MouseEnter

mOldColor = MyBase.BackColor
Me.BackColor = mMOColor

End Sub

What happens here is that the first line of the code makes a note of the color which had been chosen as the

http://www.devcity.net/PrintArticle.aspx?ArticleID=87 6/24/2008
Simple Steps in VB.NET. Building a Custom Control Page 6 of 8

BackColor property of the XtraButton. (Because the XtraButton inherits all the properties of a standard
button, it will have a BackColor property, just like any ordinary button).

The second line of code then changes the backcolor of the XtraButton to whatever color has been chosen as
the MouseOverColor.

Before we go on to test this code, we'll add another procedure that handles what happens to the XtraButton's
Backcolor when the mouse leaves:

Private Sub XB_MouseLeave(ByVal sender As Object, _


ByVal e As System.EventArgs) Handles MyBase.MouseLeave
Me.BackColor = mOldColor
End Sub

All this does is returns the XtraButton to the color it was before the mouse entered it's space.

Checkpoint
This might be a good place to see if we're heading in the right direction, so Build the XtraButton again, then
select Form1.vb[Design]. Select an XtraButton from the Toolbox and place it somewhere on the form.

Click on the instance of the button on your form and press F4 to see the Properties Window for the XtraButton
if it isn't already in view. You will see that, in addition to the properties you would normally expect to see for a
button, there is now one named MouseOverColor, which currently has a white rectangle at the side of it.

A left mouse click on this rectangle will bring you the standard color picker menu. Choose a color.

Now, run the project and move the mouse and then away from the XtraButton. If all has gone to plan, it
should change color when the mouse is over it and revert back when the mouse leaves. Try experimenting
with different MouseOverColors, as well as with the basic BackColor properties.

Also add two or three XtraButtons in a vertical line on the form and give them the same MouseOverColor. Run
the project again and you will see how it can add a kind of dynamic effect as the mouse traverses across
them.

http://www.devcity.net/PrintArticle.aspx?ArticleID=87 6/24/2008
Simple Steps in VB.NET. Building a Custom Control Page 7 of 8

Attributes
If anyone else is going to use your control, it would be useful for them to have a description of each new
property in the Properties Window. To add such a description, we will need to make some small additions to
the code.

Firstly, add this statement at the very top of the code listing in the XtraButton's code window:

Imports System.ComponentModel

This will enable you to include attributes such as Descriptions with your properties.

Now, amend the first part of the code block for the MouseOverColor Property so that it reads as follows

<Description("Gets/Sets the BackColor of Control when Mouse is over it")> _


Property MouseOverColor() as Color

Notice the final underscore in that first line; you'll get an error if you miss it out

You'll need to Build the Control once again, then you can check to see if it has worked by going back to the
Test Form Project and clicking on an XtraButton.

Now when you view the properties in the Properties Window, you will see that description is included at the
bottom.

Using Your Control in Other Projects


You probably won't want to go to the trouble of creating this control just for use in a single project, so we'll
finish off by covering how you can get access to the control in new projects.

Save and close the current project. Open a new project; choosing Windows Application from the Templates.

If you scroll down the controls in the ToolBox now you will see that the XtraButton is not there. So, we will
need to add it to the list now.

Right Click on the ToolBox. Select Customize Toolbox from the menu that appears. Choose the .Net
Framework Tab.

http://www.devcity.net/PrintArticle.aspx?ArticleID=87 6/24/2008
Simple Steps in VB.NET. Building a Custom Control Page 8 of 8

Now, click on the Browse button and navigate your way to the folder where you saved your User Control.
Open the bin Subfolder of the project. You will see the file XtraButton.dll in that folder.

Click on the Open button and the control will be added to the list of .Net Framework Components in front of
you. It should have automatically have been checked, but if it hasn't then you can do this now.

Close the Customize Toolbox menu by clicking OK. If you review the ToolBox again you will see that the
XtraButton has been added. You are now able to use this control in this (and any future) projects that you
create or use.

Moving On
From this very basic example, you will see that you can make many changes to the functionality of this
control. You could make the color of the text change when the mouse is over it, or increase the size of the
button very slightly (reverting to it's normal size when the mouse leaves). Or you can change the button color
when it is clicked or when the mouse is left to hover over it . Some of these have been included in the
attached project, but I'm sure you can think of others that you might want to incorporate yourself.

Related devCity.NET articles:

 Simple Steps in VB.NET. Part 1 - TheButton


 Simple Steps in VB.NET. Part 2 - Address Book

http://www.devcity.net/PrintArticle.aspx?ArticleID=87 6/24/2008

Вам также может понравиться