18.01.2013 Views

Mastering Visual Basic .NET

Mastering Visual Basic .NET

Mastering Visual Basic .NET

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

394<br />

Chapter 9 BUILDING CUSTOM WINDOWS CONTROLS<br />

already know how to add features like the ones described here to a TextBox from within the application’s<br />

code. But what if you want to enhance multiple TextBox controls on the same form, or reuse<br />

your code in multiple applications?<br />

The best approach is to create a new Windows control with all the desired functionality and then<br />

reuse it in multiple projects. To use the proper terminology, you can create a new custom Windows<br />

control that inherits from the TextBox control. The derived (or subclassed) control includes all the<br />

functionality of the control being inherited, plus any new features you care to add to it. This is<br />

exactly what we’re going to do in the following section.<br />

Building the FocusedTextBox Control<br />

Let’s call our new custom control FocusedTextBox. Start a new VB project and, on the New Project<br />

dialog box, select the template Windows Control Library. Name the project FocusedTextBox. The<br />

Solution Explorer for this project contains a single item, the UserControl1 item (in addition to the<br />

standard project components such as References and AssemblyInfo). UserControl1 (Figure 9.1) is<br />

the control’s surface—in a way, it’s the control’s form. This is where you’ll design the visible interface<br />

of the new control.<br />

Figure 9.1<br />

A custom control in<br />

design mode<br />

Start by renaming the UserControl1 object to FocusedTextBox. Renaming the object isn’t enough;<br />

you must also rename the class that implements the control. Open the object’s code window (click<br />

the View Code button at the top of the Solution Explorer while the UserControl1 object is selected)<br />

and change the line<br />

to<br />

Public Class UserControl1<br />

Public Class FocusedTextBox

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!