Lab 7: Creating a Custom Control

Lab 7: Creating a Custom Control

In this lab, you will create a custom control named PrettyClock. This control will display the current time on the form in a graphically rich format. You will write code to render the control, add logic to implement the functionality, add code to the constructor to set the initial properties, and test your control. The solution to this lab is available on the Supplemental Course Materials CD-ROM in the \Labs\Ch07\Solution folder.

Before You Begin

There are no prerequisites to completing this lab.

Estimated lesson time: 30 minutes

Exercise 7.1: Creating the Control

In this exercise, you will create a custom control named PrettyClock. You will inherit from the Control class and add logic to paint the control and provide properties that control its appearance. Finally you will add a timer component to provide the timekeeping functionality.

To create the project

  1. From the File menu, choose New and then choose Project. The New Project dialog box opens.

  2. In the New Project dialog box, choose Windows Application. Name your project ControlTest, and click OK.

  3. From the Project menu, choose Add New Item. The Add New Item dialog box opens.

  4. In the Add New Item dialog box, choose Custom Control and name your new item PrettyClock. Click Open to continue. A new custom control is added to your project.

  5. In Solution Explorer, right-click PrettyClock and choose View Code. The Code window opens. Note that an override of the OnPaint method is stubbed out, and comments have been added to indicate that you need to add rendering code here.

You will now add code to create the control. Your control will render the current time to the screen, surrounded by a rectangle. You will use a LinearGradientBrush to paint the control to the screen and produce interesting graphic effects. You also will add properties to your control to allow developers to set the control s visual properties at run time.

  1. At the top of the code editor, add the following lines to import the System.Drawing and System.Drawing.Drawing2D namespaces into your code:

    Visual Basic .NET

    Imports System.Drawing Imports System.Drawing.Drawing2D

    Visual C#

    // In C#, 'using System.Drawing;' is added by default using System.Drawing.Drawing2D;

  2. Add a property to hold a color value. This property, along with the ForeColor property that was inherited from control, will be used to create the LinearGradientBrush that will paint the control. Your property should look something like the following code example:

    Visual Basic .NET

    ' Adds the private variable to hold the Color value Private mForeColorTwo As Color ' Adds the property itself Public Property ForeColorTwo() As Color Get Return mForeColorTwo End Get Set(ByVal Value As Color) mForeColorTwo = Value End Set End Property

    Visual C#

    // Adds the private variable to hold the Color value private Color mForeColorTwo; // Adds the property itself public Color ForeColorTwo { get { return mForeColorTwo; } set { mForeColorTwo = value; } }

  3. Add a Single (float) property named Angle to hold the angle for the LinearGradientBrush to use. Because this will represent an angular value in degrees, include validation in the property to ensure that the property cannot be set less than 0 or greater than 360. An example of such a property follows:

    Visual Basic .NET

    Private mAngle As Single Public Property Angle() As Single Get Return mAngle End Get Set(ByVal Value As Single) ' This scheme causes the value to be set low if an attempt is ' made to set it high, and vice versa. This allows one to ' circle through the angle path by incrementing the property If Value > 360 then mAngle = 0 ElseIf Value < 0 then mAngle = 360 Else mAngle = Value End If End Set End Property

    Visual C#

    private float mAngle; public float Angle { get { return mAngle; } set { // This scheme causes the value to be set low if an attempt is // made to set it high, and vice versa. This allows one to // circle through the angle path by incrementing the property if (value > 360) mAngle = 0; else if (value < 0) mAngle = 360; else mAngle = value; } }

  4. In the OnPaint method, add code to create a LinearGradientBrush and render the current time using the control s Font object. You will use the control s Size, ForeColor, and ForeColorTwo properties to create the LinearGradientBrush. This code should all be added after the call to MyBase.OnPaint (Visual Basic .NET) or base.onPaint (Visual C#). For example:

    Visual Basic .NET

    ' This line creates a new rectangle that represents the control ' created from the origin point and the control's Size property Dim ControlRectangle As New Rectangle(New Point(0, 0), Me.Size) ' This line creates a new LinearGradientBrush that blends ' ForeColor and ForeColorTwo along the angle specified in angle. Dim myBrush As New LinearGradientBrush(ControlRectangle, _ ForeColor, ForeColorTwo, Angle) ' Creates a GraphicsPath object that will hold the text to be ' rendered Dim myPath As New GraphicsPath() ' Adds a string representing the current time to the GraphicsPath myPath.AddString(Now.ToLongTimeString(), Font.FontFamily, _ Font.Style, Font.Size, New Point(0, 0), _ StringFormat.GenericDefault) ' Renders the Graphics path pe.Graphics.FillPath(myBrush, myPath)

    Visual C#

    // This line creates a new rectangle that represents the control // created from the origin point and the control's Size property Rectangle ControlRectangle = new Rectangle(new Point(0, 0), this.Size); // This line creates a new LinearGradientBrush that blends // ForeColor and ForeColorTwo along the angle specified in angle. LinearGradientBrush myBrush = new LinearGradientBrush(ControlRectangle, ForeColor, ForeColorTwo, Angle); // Creates a GraphicsPath object that will hold the text to be // rendered GraphicsPath myPath = new GraphicsPath(); // Adds a string representing the current time to the // GraphicsPath myPath.AddString(System.DateTime.Now.ToLongTimeString(), Font.FontFamily, (int)Font.Style, Font.Size, new Point(0, 0), StringFormat.GenericDefault); // Renders the Graphics path pe.Graphics.FillPath(myBrush, myPath);

  5. Beneath the code you added in Step 4, add code to create a new Pen from the LinearGradientBrush and use it to draw a rectangle along the border of the control. Your code should be similar to the following:

    Visual Basic .NET

    ' Creates a pen from myBrush with a thickness of 8 pixels Dim myPen As New Pen(myBrush, 8) ' Renders a rectangle around the control pe.Graphics.DrawRectangle(myPen, ControlRectangle)

    Visual C#

    // Creates a pen from myBrush with a thickness of 8 pixels Pen myPen = new Pen(myBrush, 8); // Renders a rectangle around the control pe.Graphics.DrawRectangle(myPen, ControlRectangle);

  6. From the File menu, choose Save All to save your work.

You will now set start-up properties in the designer. You also will add a Timer component and add code to redraw the clock every second as well as add an interesting visual effect.

To add and configure a Timer

  1. In Solution Explorer, right-click PrettyClock and choose View Designer. The designer opens.

  2. From the Windows Forms tab of the Toolbox, drag a Timer to the designer surface.

  3. In the Properties window, set the Interval property to 1000 and the Enabled property to true.

  4. In the designer, double-click the Timer to open the Timer.Tick event handler. Add the following code:

    Visual Basic .NET

    ' This will cause the visual effect to change with each Tick Angle += 10 ' Causes the control to redraw Me.Refresh()

    Visual C#

    // This will cause the visual effect to change with each Tick Angle += 10; // Causes the control to redraw this.Refresh();

  5. In Visual C#, you must add a call to InitializeComponent to the constructor of the control to initialize your component. For example:

    Visual C#

    public PrettyClock() { InitializeComponent(); }

  6. From the File menu, choose Save All to save your work.

Exercise 7.2: Testing Your Control

Once you have created your control, you must verify that it functions as planned. In this exercise, you will add your control to the Toolbox and then add it to your form. You will configure the control in the Toolbox and observe its functionality at run time.

To add your control to the Toolbox

  1. From the Build menu, choose Build Solution to build your solution.

  2. Right-click an open space within the Toolbox, and choose Customize Toolbox. The Customize Toolbox dialog box opens.

  3. Choose the .NET Framework Components tab, and click Browse to open the Open File dialog box.

  4. Browse to the folder containing your project. In the \bin folder (Visual Basic .NET) or \bin\Debug folder (Visual C#), select ControlTest.exe, which is the compiled file that contains your control. Click OK to continue.

  5. Verify that PrettyClock is listed in the Customize Toolbox dialog box list and that the check box next to it is selected. Click OK to continue.

To test your control

  1. In Solution Explorer, right-click Form1 and choose View Designer. The designer for Form1 opens.

  2. From the General tab of the Toolbox, select PrettyClock and drag it to the form. A new instance of PrettyClock is added to the form.

  3. Set the properties of this instance of PrettyClock to the values in Table 7.8.

    Table 7-8. PrettyClock Instance Properties

    Property

    Value

    ForeColor

    Red

    ForeColorTwo

    Yellow

    Font.Size

    40

    Size

    225, 50

    Note that as you change the property values, the changes are immediately updated in the control instance in the form.

  4. In the form, verify that the time is updated every second and that the graphics blend changes every second. Press F5 to run your application. Note that the behavior at run time is the same.



MCAD(s)MCSD Self-Paced Training Kit(c) Developing Windows-Based Applications With Microsoft Visual Basic. Net a[.  .. ]0-316
MCAD(s)MCSD Self-Paced Training Kit(c) Developing Windows-Based Applications With Microsoft Visual Basic. Net a[. .. ]0-316
ISBN: 735619263
EAN: N/A
Year: 2003
Pages: 110

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net