Title: Creating .NET Controls
1Chapter 11
2Objectives
- Learn about the reasons to create a control
- Create a control by inheriting from an existing
control - Work with control attributes
- Create a control by inheriting from
System.Windows.Forms.UserControl - Aggregate and delegate properties
- Create a control by inheriting from
System.Windows.Forms.Control - Create a custom property editor
- Work with control licensing
3Reasons to Create a Control
- Three reasons
- To enhance or change the behavior of an existing
control or to hide specific properties from the
developer - To create a control that combines the features of
two or more intrinsic controls - To create an entirely new control that is not
based on a Toolbox control
4Inheriting a Control
- By inheriting from an existing control class, the
derived class inherits all of the members of the
base class - Example inheriting from the intrinsic HScrollBar
class - Public Class FractionalScrollBar
- Inherits System.Windows.Forms.HScrollBar
- End Class
5Creating a Windows Control Library Project
- Controls typically exist in their own assembly
- Multiple controls can appear in the same assembly
- Create a Windows Control Library project to
create a control assembly - Each module typically contains a separate control
6Adding a New Project
Project type
Project name
7Solution Explorer with two Projects
Windows Control Library project
Windows Application project for testing
8Compiling and Referencing a Control
- Test a control with a multi-project solution
- One project is a Windows Application project
- Second project is Windows Control Library project
- Use Customize Toolbox dialog box to reference
controls between projects
9Customize Toolbox Dialog Box
10Overriding and Extending Members of an Inherited
Control
- Overriding members
- Declare member with the Shadows keyword to hide
base class member - Call MyBase to execute base class member
- Extending members
- Declare property procedures and methods as desired
11Overriding Members of an Inherited Control
(Example)
- Shadow Value property of the base HScrollBar
class - Private msngValue As Single
- Public Shadows Property Value() As Single
- Get
- Return msngValue
- End Get
- Set(ByVal Value As Single)
- msngValue Value
- MyBase.Value ToInt32(msngValue _
- (10 (mintPrecision)))
- End Set
- End Property
12Extending Members of an Inherited Control
(Example)
- Extend HScrollBar with the Precision property
- Public Property Precision() As Integer
- Get
- Return mintPrecision
- End Get
- Set(ByVal Value As Integer)
- If Value lt 1 Or Value gt 4 Then
- Throw New _
- System.ArgumentOutOfRangeException(
_ - "Value must be between 1 and 4")
- Else
- mintPrecision Value
- End If
- End Set
- End Property
13Using Attributes with Controls (1)
- Attributes are used to alter the design time
behavior of custom controls - The Boolean Browsable attribute accepts one
argument that defines whether or not a property
should appear in the Properties window - The Category attribute is relevant when the
Categorized tab of the Properties window is
active - Defines where property appears
- The DefaultValue attribute allows you to specify
a default value for a particular property
14Using Attributes with Controls (2)
- The DefaultProperty attribute allows you to
define the property that will be selected, by
default, when the developer activates the
Properties window - This property is selected when the Properties
window is first activated - The Editor attribute is used to define a class
that will operate as a custom property editor
15Using Attributes with Controls (3)
- The Localizable attribute defines whether or not
a property can be localized - The Boolean MergableProperty attribute defines
whether or not the property will appear in the
Properties window when multiple control instances
are selected - The RefreshProperties attribute defines how the
visual designer should refresh other properties
appearing in the Properties window - Valid values are All, None, and Repaint
16Single Attribute (Example)
- Set the Category attribute
- Note attribute appears in ltgt and argument appears
in parentheses - Attribute is part of the property declaration
- ltCategory("Behavior")gt _
- Public Property Precision() As Integer
- ' Statements
- End Property
17Multiple Attributes (Example)
- Set multiple attributes
- A comma separates each attribute name
- Less-than and greater-than signs surround the
attribute list - ltDefaultValue(2), _
- Description("The decimal precision."), _
- Category("Behavior"), _
- MergableProperty(False)gt _
- Public Property Precision() As Integer
- ' Statements
- End Property
18Class Level Attributes
- The following attributes apply to the class
rather than a specific member - The Description attribute contains a string
- The value of this string appears in the
Description section at the bottom of the
Properties window - The ToolboxBitmap attribute defines the bitmap
that appears in the Toolbox
19System.Windows.Forms.UserControl (Properties )
- The Boolean DesignMode property of the base
Component class, if True, signifies that the
control is in design mode. If False, the control
is running - The ForeColor and BackColor properties define the
foreground and background colors of the control,
respectively - The ClientRectangle property returns a Rectangle
structure representing the client area of the
control instance - The ClientSize property returns the height and
width of the client area
20System.Windows.Forms.UserControl(Methods and
Events)
- Methods
- The BringToFront and SendToBack methods reorder
the control instance in the z-order - Events
- UserControl supports mouse events such as
MouseOver, MouseUp, and MouseDown - UserControl supports keyboard events such as
KeyUp, KeyDown, and KeyPress - Resize event fires when the developer resizes the
UserControl
21UserControl Designer
- UserControl designer supplies a visual drawing
surface on which constituent controls are created - Constituent control is nothing more than an
existing intrinsic control - Create multiple constituent controls, as
necessary - Set properties of the UserControl and constituent
control just as you would with a form
22UserControl Designer (Illustration)
UserControl Designer
Constituent Label control instance
Constituent TextBox control instance
23Ambient Properties
- Properties of a constituent control are hidden
from the developer - Ambient properties are properties of the
UserControl itself - BackColor, ForeColor, Dock, and Anchor are
ambient properties
24Delegating andAggregating Properties
- Delegation exposes a single property of a
constituent control - Delegate Text property of a TextBox for example
- Aggregation is used to group properties when
building a control from multiple constituent
controls - Aggregate ForeColor property of a TextBox and
Label, for example
25Delegation and Aggregation (Illustration)
26Hiding a Property
- .NET supplies no direct means to hide a property
from a developer - Hide a property by
- Setting the Browsable attribute to False
- Check Me.DesignMode and throw an exception if the
developer tries to set the property's value
27Hiding a Property (Example)
- Hide the AutoScroll Property
- Public Shadows Property AutoScroll() As Boolean
- Get
- If Not Me.DesignMode Then
- Throw New System.NotImplementedExcepti
on() - End If
- End Get
- Set(ByVal Value As Boolean)
- If Not Me.DesignMode Then
- Throw New System.NotImplementedExcepti
on() - End If
- End Set
- End Property
28Inheriting fromSystem.Windows.Forms.Control
- Create a control from scratch by inheriting a
class from System.Windows.Forms.Control - When you create a control from scratch, you must
write the statements to paint the control - Creating a control from scratch is the most
difficult control creation technique - No visual designer is supported
29System.Windows.Forms.Control
- Intrinsic controls appearing in the Toolbox and
the UserControl class all ultimately derive from
System.Windows.Forms.Control - Members of the Control class define the size of
the control instance as it will appear on a
visual surface (form) - Other members define the color and appearance of
the control - The Control class itself does not define how the
control will be painted - Create a Paint event handler and paint the
control instance as necessary
30Creating a CustomProperty Editor (1)
- Custom property editors override the default
behavior of a property appearing in the
Properties window - The System.Drawing.Design namespace contains
classes that define existing property editors - The classes of the System.Windows.Forms.Design
namespace extend the design-time support for
forms and controls
31Creating a CustomProperty Editor (Illustration)
32Creating a CustomProperty Editor
- Creating and using a custom property editor and
associating it with an existing property is a
two-step process - First, create a class that derives from the
UITypeEditor class - Second, supply an attribute to a specific
property so that the VB .NET design-time
environment will be able to use the custom
property editor
33Creating a CustomProperty Editor (Example)
- Set the Editor attribute to the custom class that
implements the custom property editor - Second argument is of type UITypeEditor
- ltEditor(GetType(ThicknessEditor),GetType(UITypeEdi
tor))gt _ - Public Property Thickness() As Integer
- Public Class ThicknessEditor
- Inherits UITypeEditor
- End Class
34UITypeEditor Class
- UITypeEditor class supplies two methods that are
significant in creating a custom property editor - The GetEditStyle method determines the editor
style used to edit the specified property - The EditValue method is responsible for creating
the control instance that will be used to edit a
value in the Properties window
35UITypeEditor Class
- The following statements override the
GetEditStyle method of the base UITypeEditor
class - Public Overloads Overrides Function
GetEditStyle( _ - ByVal context As _
- System.ComponentModel.ITypeDescriptorContext) _
- As System.Drawing.Design.UITypeEditorEditStyle
-
- If Not (context Is Nothing) _
- AndAlso Not (context.Instance Is Nothing)
Then - Return UITypeEditorEditStyle.DropDown
- Else
- Return MyBase.GetEditStyle(context)
- End If
- End Function
36Operation of aCustom Property Editor
37Supported CustomProperty Editor Styles
- Three types of custom property editor styles are
supported - If a DropDown style editor is used, the
Properties window will display a list arrow at
the right side of the Value column - If a Modal style editor is used, ellipses will
appear in the Properties window and a modal
dialog box will appear as a result of editing the
property - If set to None, no custom property editor will
appear in the Properties window
38Control Licensing
- Control licensing prevents unauthorized use of a
control - Two options to supply licensing for a control
- Use the built-in license provider supplied by VB
.NET - Create a custom license provider
39Using the Built-In LicFileLicenseProvider (1)
- Easiest way to license a control is to use the
LicenseProvider attribute and the built-in
LicFileLicenseProvider class - Example of built-in LicenseProvider attribute
- ltLicenseProvider(GetType(LicFileLicenseProvider))
gt _ - Public Class SuperText
40Using the Built-In LicFileLicenseProvider (2)
- Dissection
- The LicenseProvider attribute creates an instance
of the built-in LicFileLicenseProvider class - The LicenseProvider constructor accepts one
argument - The class that manages the license itself
41Using the Built-In LicFileLicenseProvider (3)
- Shared LicenseManager class belongs to the
System.ComponentModel namespace - Call the Validate method in the constructor to
validate the license - Private licCurrent As License
- Public Sub New()
- MyBase.New()
- InitializeComponent()
- licCurrent LicenseManager.Validate _
(GetType(SuperText), Me) - End Sub
42Using the Built-In LicFileLicenseProvider (4)
- Usage
- The license is validated in the constructor for
the class - The Validate method of the LicenseManager class
checks to see whether or not a valid license
exists - The Validate method accomplishes this task by
reading the license file corresponding to the
control
43Destroying a License Manager
- When the control instance is destroyed you must
destroy the license - Call the Dispose method to destroy a license
- If Not (licCurrent Is Nothing) Then
- licCurrent.Dispose()
- licCurrent Nothing
- End If
44Creating and Destroying aLicense Manager
(Illustration)
45Licensing Error
- Dialog box appears if the license cannot be
granted
46The Environment Class
- The Environment class supplies the means to
obtain information about the computers
configuration - Windows system directory
- Environment variables
47Environment Class (Properties and Methods)
- Properties
- The CurrentDirectory property gets the directory
from which the process (application) started - The SystemDirectory property gets the path name
of the Windows system directory - Methods
- The GetEnvironmentVariable method gets the value
of a specific environment variable, such as the
path - The GetEnvironmentVariables method gets all of
the defined environment variables
48Creating a CustomLicense Provider
- The steps to create a custom license provider
- Require that you create a class that inherits
from the abstract LicenseProvider class - The LicenseProvider class supplies an abstract
method named GetLicense that you must implement - It is the responsibility of this method to load
and process the license file
49Custom License Provider Example
- Example
- Public Class LicCustomFileLicenseProvider
- Inherits LicenseProvider
- Public Overrides Function GetLicense( _
- ByVal context As LicenseContext, _
- ByVal typ As System.Type, _
- ByVal instance As Object, _
- ByVal allowExceptions As Boolean) As License
- Public Class DesignTimeLicense
- Inherits License
- End Class
- Public Class RunTimeLicense
- Inherits License
- End Class
- End Class
50GetLicense Method (1)
- GetLicense arguments
- The LicenseContext argument specifies when the
license can be used. The UsageMode property of
the LicenseContext class has enumeration values
of LicenseUsageMode.Runtime and
LicenseUsageMode.Designtime for runtime and
design-time licenses, respectively - The type of the component requesting the license
appears in the second argument, having a data
type of System.Type
51GetLicense Method (2)
- GetLicense arguments
- The third argument has a data type of
System.Object - This argument contains an instance of the
component that is requesting the license - The final argument has a data type of Boolean
- A value of True indicates that an exception
should be thrown if the component cannot be
granted a license and False otherwise