Professional Documents
Culture Documents
http://msdn.microsoft.com/en-us/library/35ea88wb
Walkthrough: Creating a Windows Forms Control That Takes Advantage of Visual Studio Design-Time Features
Visual Studio 2010 1 out of 2 rated this helpful - Rate this topic Updated: July 2010 The design-time experience for a custom control can be enhanced by authoring an associated custom designer. This walkthrough illustrates how to create a custom designer for a custom control. You will implement a MarqueeControl type and an associated designer class, called MarqueeControlRootDesigner. The MarqueeControl type implements a display similar to a theater marquee, with animated lights and flashing text. The designer for this control interacts with the design environment to provide a custom design-time experience. With the custom designer, you can assemble a custom MarqueeControl implementation with animated lights and flashing text in many combinations. You can use the assembled control on a form like any other Windows Forms control. Tasks illustrated in this walkthrough include: Creating the Project Creating a Control Library Project Referencing the Custom Control Project Defining a Custom Control and Its Custom Designer Creating an Instance of Your Custom Control Setting Up the Project for Design-Time Debugging Implementing Your Custom Control Creating a Child Control for Your Custom Control Create the MarqueeBorder Child Control Creating a Custom Designer to Shadow and Filter Properties Handling Component Changes Adding Designer Verbs to your Custom Designer Creating a Custom UITypeEditor Testing your Custom Control in the Designer When you are finished, your custom control will look something like the following:
1 of 36
5/25/2012 11:39 AM
http://msdn.microsoft.com/en-us/library/35ea88wb
For the complete code listing, see How to: Create a Windows Forms Control That Takes Advantage of Design-Time Features.
Note
The dialog boxes and menu commands you see might differ from those described in Help depending on your active settings or edition. To change your settings, choose Import and Export Settings on the Tools menu. For more information, see Working with Settings.
Prerequisites
In order to complete this walkthrough, you will need: Sufficient permissions to be able to create and run Windows Forms application projects on the computer where Visual Studio is installed.
2 of 36
5/25/2012 11:39 AM
http://msdn.microsoft.com/en-us/library/35ea88wb
5. Right-click the Design folder and add a new class. Give the source file a base name of "MarqueeControlRootDesigner." 6. You will need to use types from the System.Design assembly, so add this reference to the MarqueeControlLibrary project.
Note
To use the System.Design assembly, your project must target the full version of the .NET Framework, not the .NET Framework Client Profile. To change the target framework, see How to: Target a Specific .NET Framework Version or Profile.
2. Add the DesignerAttribute to the MarqueeControl class declaration. This associates the custom control with its designer.
3 of 36
5/25/2012 11:39 AM
http://msdn.microsoft.com/en-us/library/35ea88wb
3. Open the MarqueeControlRootDesigner source file in the Code Editor. At the top of the file, import the following namespaces: C# using using using using using using using using System; System.Collections; System.ComponentModel; System.ComponentModel.Design; System.Diagnostics; System.Drawing.Design; System.Windows.Forms; System.Windows.Forms.Design;
4. Change the declaration of MarqueeControlRootDesigner to inherit from the DocumentDesigner class. Apply the ToolboxItemFilterAttribute to specify the designer interaction with the Toolbox. Note The definition for the MarqueeControlRootDesigner class has been enclosed in a namespace called "MarqueeControlLibrary.Design." This declaration places the designer in a special namespace reserved for design-related types. C#
namespace MarqueeControlLibrary.Design { [ToolboxItemFilter("MarqueeControlLibrary.MarqueeBorder", ToolboxItemFilterType.Require)] [ToolboxItemFilter("MarqueeControlLibrary.MarqueeText", ToolboxItemFilterType.Require)] [System.Security.Permissions.PermissionSet(System.Security.Permissions.SecurityAction.Demand public class MarqueeControlRootDesigner : DocumentDesigner {
5. Define the constructor for the MarqueeControlRootDesigner class. Insert a WriteLine statement in the constructor body. This will be useful for debugging purposes. C# public MarqueeControlRootDesigner() { Trace.WriteLine("MarqueeControlRootDesigner ctor"); }
4 of 36
5/25/2012 11:39 AM
http://msdn.microsoft.com/en-us/library/35ea88wb
Checkpoint
You are now ready to debug the design-time behavior of your custom control. Once you have determined that the debugging environment is set up correctly, you will test the association between
5 of 36
5/25/2012 11:39 AM
Walkthrough: Creating a Windows Forms Control That Takes Advantage ... the custom control and the custom designer.
http://msdn.microsoft.com/en-us/library/35ea88wb
6 of 36
5/25/2012 11:39 AM
http://msdn.microsoft.com/en-us/library/35ea88wb
public void Stop() { // The MarqueeControl may contain any number of // controls that implement IMarqueeWidget, so find // each IMarqueeWidget child and call its StopMarquee // method. foreach( Control cntrl in this.Controls ) { if( cntrl is IMarqueeWidget ) { IMarqueeWidget widget = cntrl as IMarqueeWidget; widget.StopMarquee(); } } }
2. Override the OnLayout method. C# protected override void OnLayout(LayoutEventArgs levent) { base.OnLayout (levent); // Repaint all IMarqueeWidget children if the layout // has changed. foreach( Control cntrl in this.Controls ) { if( cntrl is IMarqueeWidget ) { Control control = cntrl as Control; } control.PerformLayout();
MarqueeBorder: This control paints a border of "lights" around its edges. The lights flash in sequence, so they appear to be moving around the border. The speed at which the lights flash is controlled by a property called UpdatePeriod. Several other custom properties determine other aspects of the control's appearance. Two methods, called StartMarquee and StopMarquee, control when the animation starts and stops.
7 of 36
5/25/2012 11:39 AM
http://msdn.microsoft.com/en-us/library/35ea88wb
MarqueeText: This control paints a flashing string. Like the MarqueeBorder control, the speed at which the text flashes is controlled by the UpdatePeriod property. The MarqueeText control also has the StartMarquee and StopMarquee methods in common with the MarqueeBorder control.
At design time, the MarqueeControlRootDesigner allows these two control types to be added to a MarqueeControl in any combination. Common features of the two controls are factored into an interface called IMarqueeWidget. This allows the MarqueeControl to discover any Marquee-related child controls and give them special treatment. To implement the periodic animation feature, you will use BackgroundWorker objects from the System.ComponentModel namespace. You could use Timer objects, but when many IMarqueeWidget objects are present, the single UI thread may be unable to keep up with the animation.
3. Add the following code to the IMarqueeWidget interface to expose two methods and a property that manipulate the marquee animation: C# // This interface defines the contract for any class that is to // be used in constructing a MarqueeControl. public interface IMarqueeWidget { // This method starts the animation. If the control can // contain other classes that implement IMarqueeWidget as // children, the control should call StartMarquee on all // its IMarqueeWidget child controls. void StartMarquee(); // This method stops the animation. If the control can // contain other classes that implement IMarqueeWidget as // children, the control should call StopMarquee on all // its IMarqueeWidget child controls. void StopMarquee(); // This method specifies the refresh rate for the animation,
8 of 36
5/25/2012 11:39 AM
Walkthrough: Creating a Windows Forms Control That Takes Advantage ... // in milliseconds. int UpdatePeriod { get; set; }
http://msdn.microsoft.com/en-us/library/35ea88wb
4. Add a new Custom Control item to the MarqueeControlLibrary project. Give the new source file a base name of "MarqueeText." 5. Drag a BackgroundWorker component from the Toolbox onto your MarqueeText control. This component will allow the MarqueeText control to update itself asynchronously. 6. In the Properties window, set the BackgroundWorker component's WorkerReportsProgess and WorkerSupportsCancellation properties to true. These settings allow the BackgroundWorker component to periodically raise the ProgressChanged event and to cancel asynchronous updates. For more information, see BackgroundWorker Component. 7. Open the MarqueeText source file in the Code Editor. At the top of the file, import the following namespaces: C# using using using using using using using using System; System.ComponentModel; System.ComponentModel.Design; System.Diagnostics; System.Drawing; System.Threading; System.Windows.Forms; System.Windows.Forms.Design;
8. Change the declaration of MarqueeText to inherit from Label and to implement the IMarqueeWidget interface: C# [ToolboxItemFilter("MarqueeControlLibrary.MarqueeText", ToolboxItemFilterType.Require)] public partial class MarqueeText : Label, IMarqueeWidget {
9. Declare the instance variables that correspond to the exposed properties, and initialize them in the constructor. The isLit field determines if the text is to be painted in the color given by the LightColor property. C#
9 of 36
5/25/2012 11:39 AM
http://msdn.microsoft.com/en-us/library/35ea88wb
// When isLit is true, the text is painted in the light color; // When isLit is false, the text is painted in the dark color. // This value changes whenever the BackgroundWorker component // raises the ProgressChanged event. private bool isLit = true; // These fields back the public properties. private int updatePeriodValue = 50; private Color lightColorValue; private Color darkColorValue; // These brushes are used to paint the light and dark // colors of the text. private Brush lightBrush; private Brush darkBrush; // This component updates the control asynchronously. private BackgroundWorker backgroundWorker1; public MarqueeText() { // This call is required by the Windows.Forms Form Designer. InitializeComponent(); // Initialize light and dark colors // to the control's default values. this.lightColorValue = this.ForeColor; this.darkColorValue = this.BackColor; this.lightBrush = new SolidBrush(this.lightColorValue); this.darkBrush = new SolidBrush(this.darkColorValue);
10. Implement the IMarqueeWidget interface. The StartMarquee and StopMarquee methods invoke the BackgroundWorker component's RunWorkerAsync and CancelAsync methods to start and stop the animation. The Category and Browsable attributes are applied to the UpdatePeriod property so it appears in a custom section of the Properties window called "Marquee." C# public virtual void StartMarquee() { // Start the updating thread and pass it the UpdatePeriod. this.backgroundWorker1.RunWorkerAsync(this.UpdatePeriod); } public virtual void StopMarquee() { // Stop the updating thread. this.backgroundWorker1.CancelAsync(); } [Category("Marquee")]
10 of 36
5/25/2012 11:39 AM
Walkthrough: Creating a Windows Forms Control That Takes Advantage ... [Browsable(true)] public int UpdatePeriod { get { return this.updatePeriodValue; } set {
http://msdn.microsoft.com/en-us/library/35ea88wb
if (value > 0) { this.updatePeriodValue = value; } else { throw new ArgumentOutOfRangeException("UpdatePeriod", "must be > 0"); }
11. Implement the property accessors. You will expose two properties to clients: LightColor and DarkColor. The Category and Browsable attributes are applied to these properties, so the properties appear in a custom section of the Properties window called "Marquee." C# [Category("Marquee")] [Browsable(true)] public Color LightColor { get { return this.lightColorValue; } set { // The LightColor property is only changed if the // client provides a different value. Comparing values // from the ToArgb method is the recommended test for // equality between Color structs. if (this.lightColorValue.ToArgb() != value.ToArgb()) { this.lightColorValue = value; this.lightBrush = new SolidBrush(value); } } } [Category("Marquee")] [Browsable(true)] public Color DarkColor { get
11 of 36
5/25/2012 11:39 AM
Walkthrough: Creating a Windows Forms Control That Takes Advantage ... { } set {
http://msdn.microsoft.com/en-us/library/35ea88wb
return this.darkColorValue;
// // // // if { }
The DarkColor property is only changed if the client provides a different value. Comparing values from the ToArgb method is the recommended test for equality between Color structs. (this.darkColorValue.ToArgb() != value.ToArgb()) this.darkColorValue = value; this.darkBrush = new SolidBrush(value);
12. Implement the handlers for the BackgroundWorker component's DoWork and ProgressChanged events. The DoWork event handler sleeps for the number of milliseconds specified by UpdatePeriod then raises the ProgressChanged event, until your code stops the animation by calling CancelAsync. The ProgressChanged event handler toggles the text between its light and dark state to give the appearance of flashing. C# // This method is called in the worker thread's context, // so it must not make any calls into the MarqueeText control. // Instead, it communicates to the control using the // ProgressChanged event. // // The only work done in this event handler is // to sleep for the number of milliseconds specified // by UpdatePeriod, then raise the ProgressChanged event. private void backgroundWorker1_DoWork( object sender, System.ComponentModel.DoWorkEventArgs e) { BackgroundWorker worker = sender as BackgroundWorker; // This event handler will run until the client cancels // the background task by calling CancelAsync. while (!worker.CancellationPending) { // The Argument property of the DoWorkEventArgs // object holds the value of UpdatePeriod, which // was passed as the argument to the RunWorkerAsync // method. Thread.Sleep((int)e.Argument); // The DoWork eventhandler does not actually report // progress; the ReportProgress event is used to
12 of 36
5/25/2012 11:39 AM
http://msdn.microsoft.com/en-us/library/35ea88wb
// The ProgressChanged event is raised by the DoWork method. // This event handler does work that is internal to the // control. In this case, the text is toggled between its // light and dark state, and the control is told to // repaint itself. private void backgroundWorker1_ProgressChanged(object sender, System.ComponentModel.Prog { this.isLit = !this.isLit; this.Refresh(); }
13. Override the OnPaint method to enable the animation. C# protected override void OnPaint(PaintEventArgs e) { // The text is painted in the light or dark color, // depending on the current value of isLit. this.ForeColor = this.isLit ? this.lightColorValue : this.darkColorValue; } base.OnPaint(e);
13 of 36
5/25/2012 11:39 AM
http://msdn.microsoft.com/en-us/library/35ea88wb
asynchronous updates. For more information, see BackgroundWorker Component. 4. In the Properties window, click the Events button. Attach handlers for the DoWork and ProgressChanged events. 5. Open the MarqueeBorder source file in the Code Editor. At the top of the file, import the following namespaces: C# using using using using using using using using using System; System.ComponentModel; System.ComponentModel.Design; System.Diagnostics; System.Drawing; System.Drawing.Design; System.Threading; System.Windows.Forms; System.Windows.Forms.Design;
6. Change the declaration of MarqueeBorder to inherit from Panel and to implement the IMarqueeWidget interface. C# [Designer(typeof(MarqueeControlLibrary.Design.MarqueeBorderDesigner ))] [ToolboxItemFilter("MarqueeControlLibrary.MarqueeBorder", ToolboxItemFilterType.Require)] public partial class MarqueeBorder : Panel, IMarqueeWidget {
7. Declare two enumerations for managing the MarqueeBorder control's state: MarqueeSpinDirection, which determines the direction in which the lights "spin" around the border, and MarqueeLightShape, which determines the shape of the lights (square or circular). Place these declarations before the MarqueeBorder class declaration. C# // This defines the possible values for the MarqueeBorder // control's SpinDirection property. public enum MarqueeSpinDirection { CW, CCW } // This defines the possible values for the MarqueeBorder // control's LightShape property. public enum MarqueeLightShape { Square,
14 of 36
5/25/2012 11:39 AM
Walkthrough: Creating a Windows Forms Control That Takes Advantage ... Circle
http://msdn.microsoft.com/en-us/library/35ea88wb
8. Declare the instance variables that correspond to the exposed properties, and initialize them in the constructor. C# public static int MaxLightSize = 10; // These fields back the public properties. private int updatePeriodValue = 50; private int lightSizeValue = 5; private int lightPeriodValue = 3; private int lightSpacingValue = 1; private Color lightColorValue; private Color darkColorValue; private MarqueeSpinDirection spinDirectionValue = MarqueeSpinDirection.CW; private MarqueeLightShape lightShapeValue = MarqueeLightShape.Square; // These brushes are used to paint the light and dark // colors of the marquee lights. private Brush lightBrush; private Brush darkBrush; // This field tracks the progress of the "first" light as it // "travels" around the marquee border. private int currentOffset = 0; // This component updates the control asynchronously. private System.ComponentModel.BackgroundWorker backgroundWorker1; public MarqueeBorder() { // This call is required by the Windows.Forms Form Designer. InitializeComponent(); // Initialize light and dark colors // to the control's default values. this.lightColorValue = this.ForeColor; this.darkColorValue = this.BackColor; this.lightBrush = new SolidBrush(this.lightColorValue); this.darkBrush = new SolidBrush(this.darkColorValue); // The MarqueeBorder control manages its own padding, // because it requires that any contained controls do // not overlap any of the marquee lights. int pad = 2 * (this.lightSizeValue + this.lightSpacingValue); this.Padding = new Padding(pad, pad, pad, pad); } SetStyle(ControlStyles.OptimizedDoubleBuffer, true);
15 of 36
5/25/2012 11:39 AM
Walkthrough: Creating a Windows Forms Control That Takes Advantage ... 9. Implement the IMarqueeWidget interface.
http://msdn.microsoft.com/en-us/library/35ea88wb
The StartMarquee and StopMarquee methods invoke the BackgroundWorker component's RunWorkerAsync and CancelAsync methods to start and stop the animation. Because the MarqueeBorder control can contain child controls, the StartMarquee method enumerates all child controls and calls StartMarquee on those that implement IMarqueeWidget. The StopMarquee method has a similar implementation. C# public virtual void StartMarquee() { // The MarqueeBorder control may contain any number of // controls that implement IMarqueeWidget, so find // each IMarqueeWidget child and call its StartMarquee // method. foreach (Control cntrl in this.Controls) { if (cntrl is IMarqueeWidget) { IMarqueeWidget widget = cntrl as IMarqueeWidget; widget.StartMarquee(); } } // Start the updating thread and pass it the UpdatePeriod. this.backgroundWorker1.RunWorkerAsync(this.UpdatePeriod);
public virtual void StopMarquee() { // The MarqueeBorder control may contain any number of // controls that implement IMarqueeWidget, so find // each IMarqueeWidget child and call its StopMarquee // method. foreach (Control cntrl in this.Controls) { if (cntrl is IMarqueeWidget) { IMarqueeWidget widget = cntrl as IMarqueeWidget; widget.StopMarquee(); } } // Stop the updating thread. this.backgroundWorker1.CancelAsync();
16 of 36
5/25/2012 11:39 AM
http://msdn.microsoft.com/en-us/library/35ea88wb
set {
if (value > 0) { this.updatePeriodValue = value; } else { throw new ArgumentOutOfRangeException("UpdatePeriod", "must be > 0" }
10. Implement the property accessors. The MarqueeBorder control has several properties for controlling its appearance. C# [Category("Marquee")] [Browsable(true)] public int LightSize { get { return this.lightSizeValue; } set {
if (value > 0 && value <= MaxLightSize) { this.lightSizeValue = value; this.DockPadding.All = 2 * value; } else { throw new ArgumentOutOfRangeException("LightSize", "must be > 0 and < MaxLig }
17 of 36
5/25/2012 11:39 AM
http://msdn.microsoft.com/en-us/library/35ea88wb
if (value > 0) { this.lightPeriodValue = value; } else { throw new ArgumentOutOfRangeException("LightPeriod", "must be > 0 " }
// // // // if { }
The LightColor property is only changed if the client provides a different value. Comparing values from the ToArgb method is the recommended test for equality between Color structs. (this.lightColorValue.ToArgb() != value.ToArgb()) this.lightColorValue = value; this.lightBrush = new SolidBrush(value);
// // // // if { }
The DarkColor property is only changed if the client provides a different value. Comparing values from the ToArgb method is the recommended test for equality between Color structs. (this.darkColorValue.ToArgb() != value.ToArgb()) this.darkColorValue = value; this.darkBrush = new SolidBrush(value);
18 of 36
5/25/2012 11:39 AM
Walkthrough: Creating a Windows Forms Control That Takes Advantage ... [Category("Marquee")] [Browsable(true)] public int LightSpacing { get { return this.lightSpacingValue; } set {
http://msdn.microsoft.com/en-us/library/35ea88wb
if (value >= 0) { this.lightSpacingValue = value; } else { throw new ArgumentOutOfRangeException("LightSpacing", "must be >= 0" }
[Category("Marquee")] [Browsable(true)] [EditorAttribute(typeof(LightShapeEditor), typeof(System.Drawing.Design.UITypeEditor))] public MarqueeLightShape LightShape { get { return this.lightShapeValue; } set { } }
this.lightShapeValue = value;
this.spinDirectionValue = value;
19 of 36
5/25/2012 11:39 AM
http://msdn.microsoft.com/en-us/library/35ea88wb
11. Implement the handlers for the BackgroundWorker component's DoWork and ProgressChanged events. The DoWork event handler sleeps for the number of milliseconds specified by UpdatePeriod then raises the ProgressChanged event, until your code stops the animation by calling CancelAsync. The ProgressChanged event handler increments the position of the "base" light, from which the light/dark state of the other lights is determined, and calls the Refresh method to cause the control to repaint itself. C# // This method is called in the worker thread's context, // so it must not make any calls into the MarqueeBorder // control. Instead, it communicates to the control using // the ProgressChanged event. // // The only work done in this event handler is // to sleep for the number of milliseconds specified // by UpdatePeriod, then raise the ProgressChanged event. private void backgroundWorker1_DoWork(object sender, System.ComponentModel.DoWorkEventArgs e) { BackgroundWorker worker = sender as BackgroundWorker; // This event handler will run until the client cancels // the background task by calling CancelAsync. while (!worker.CancellationPending) { // The Argument property of the DoWorkEventArgs // object holds the value of UpdatePeriod, which // was passed as the argument to the RunWorkerAsync // method. Thread.Sleep((int)e.Argument); // The DoWork eventhandler does not actually report // progress; the ReportProgress event is used to // periodically alert the control to update its state. worker.ReportProgress(0);
// The ProgressChanged event is raised by the DoWork method. // This event handler does work that is internal to the // control. In this case, the currentOffset is incremented, // and the control is told to repaint itself. private void backgroundWorker1_ProgressChanged( object sender, System.ComponentModel.ProgressChangedEventArgs e) { this.currentOffset++; this.Refresh(); }
20 of 36
5/25/2012 11:39 AM
http://msdn.microsoft.com/en-us/library/35ea88wb
The IsLit method determines the color of a light at a given position. Lights that are "lit" are drawn in the color given by the LightColor property, and those that are "dark" are drawn in the color given by the DarkColor property. The DrawLight method draws a light using the appropriate color, shape, and position. C# // This method determines if the marquee light at lightIndex // should be lit. The currentOffset field specifies where // the "first" light is located, and the "position" of the // light given by lightIndex is computed relative to this // offset. If this position modulo lightPeriodValue is zero, // the light is considered to be on, and it will be painted // with the control's lightBrush. protected virtual bool IsLit(int lightIndex) { int directionFactor = (this.spinDirectionValue == MarqueeSpinDirection.CW ? -1 : 1); return ( (lightIndex + directionFactor * this.currentOffset) % this.lightPeriodValue == 0 );
protected virtual void DrawLight( Graphics g, Brush brush, int xPos, int yPos) { switch (this.lightShapeValue) { case MarqueeLightShape.Square: { g.FillRectangle(brush, xPos, yPos, this.lightSizeValue, this.lightSizeValue); break; } case MarqueeLightShape.Circle: { g.FillEllipse(brush, xPos, yPos, this.lightSizeValue, this.lightSizeValue); break; } default: { Trace.Assert(false, "Unknown value for light shape."); break; } } }
13. Override the OnLayout and OnPaint methods. The OnPaint method draws the lights along the edges of the MarqueeBorder control.
21 of 36
5/25/2012 11:39 AM
http://msdn.microsoft.com/en-us/library/35ea88wb
Because the OnPaint method depends on the dimensions of the MarqueeBorder control, you need to call it whenever the layout changes. To achieve this, override OnLayout and call Refresh. C# protected override void OnLayout(LayoutEventArgs levent) { base.OnLayout(levent); // Repaint when the layout has changed. this.Refresh();
// This method paints the lights around the border of the // control. It paints the top row first, followed by the // right side, the bottom row, and the left side. The color // of each light is determined by the IsLit method and // depends on the light's position relative to the value // of currentOffset. protected override void OnPaint(PaintEventArgs e) { Graphics g = e.Graphics; g.Clear(this.BackColor); base.OnPaint(e); // If the control is large enough, draw some lights. if (this.Width > MaxLightSize && this.Height > MaxLightSize) { // The position of the next light will be incremented // by this value, which is equal to the sum of the // light size and the space between two lights. int increment = this.lightSizeValue + this.lightSpacingValue; // Compute the number of lights to be drawn along the // horizontal edges of the control. int horizontalLights = (this.Width - increment) / increment; // Compute the number of lights to be drawn along the // vertical edges of the control. int verticalLights = (this.Height - increment) / increment; // These local variables will be used to position and // paint each light. int xPos = 0; int yPos = 0; int lightCounter = 0; Brush brush; // Draw the top row of lights. for (int i = 0; i < horizontalLights; i++)
22 of 36
5/25/2012 11:39 AM
http://msdn.microsoft.com/en-us/library/35ea88wb
brush = IsLit(lightCounter) ? this.lightBrush : this.darkBrush; DrawLight(g, brush, xPos, yPos); xPos += increment; lightCounter++;
// Draw the lights flush with the right edge of the control. xPos = this.Width - this.lightSizeValue; // Draw the right column of lights. for (int i = 0; i < verticalLights; i++) { brush = IsLit(lightCounter) ? this.lightBrush : this.darkBrush; DrawLight(g, brush, xPos, yPos); yPos += increment; lightCounter++;
// Draw the lights flush with the bottom edge of the control. yPos = this.Height - this.lightSizeValue; // Draw the bottom row of lights. for (int i = 0; i < horizontalLights; i++) { brush = IsLit(lightCounter) ? this.lightBrush : this.darkBrush; DrawLight(g, brush, xPos, yPos); xPos -= increment; lightCounter++;
// Draw the lights flush with the left edge of the control. xPos = 0; // Draw the left column of lights. for (int i = 0; i < verticalLights; i++) { brush = IsLit(lightCounter) ? this.lightBrush : this.darkBrush; DrawLight(g, brush, xPos, yPos); yPos -= increment; lightCounter++;
http://msdn.microsoft.com/en-us/library/35ea88wb
The MarqueeControlRootDesigner class provides the implementation for the root designer. In addition to this designer, which operates on the MarqueeControl, you will need a custom designer that is specifically associated with the MarqueeBorder control. This designer provides custom behavior that is appropriate in the context of the custom root designer. Specifically, the MarqueeBorderDesigner will "shadow" and filter certain properties on the MarqueeBorder control, changing their interaction with the design environment. Intercepting calls to a component's property accessor is known as "shadowing." It allows a designer to track the value set by the user and optionally pass that value to the component being designed. For this example, the Visible and Enabled properties will be shadowed by the MarqueeBorderDesigner, which prevents the user from making the MarqueeBorder control invisible or disabled during design time. Designers can also add and remove properties. For this example, the Padding property will be removed at design time, because the MarqueeBorder control programmatically sets the padding based on the size of the lights specified by the LightSize property. The base class for MarqueeBorderDesigner is ComponentDesigner, which has methods that can change the attributes, properties, and events exposed by a control at design time: PreFilterProperties PostFilterProperties PreFilterAttributes PostFilterAttributes PreFilterEvents PostFilterEvents When changing the public interface of a component using these methods, you must follow these rules: Add or remove items in the PreFilter methods only Modify existing items in the PostFilter methods only Always call the base implementation first in the PreFilter methods Always call the base implementation last in the PostFilter methods Adhering to these rules ensures that all designers in the design-time environment have a consistent view of all components being designed. The ComponentDesigner class provides a dictionary for managing the values of shadowed properties, which relieves you of the need to create specific instance variables.
24 of 36
5/25/2012 11:39 AM
http://msdn.microsoft.com/en-us/library/35ea88wb
3. Change the declaration of MarqueeBorderDesigner to inherit from ParentControlDesigner. Because the MarqueeBorder control can contain child controls, MarqueeBorderDesigner inherits from ParentControlDesigner, which handles the parent-child interaction. C#
4. Override the base implementation of PreFilterProperties. C# protected override void PreFilterProperties(IDictionary properties) { base.PreFilterProperties(properties); if (properties.Contains("Padding")) { properties.Remove("Padding"); } properties["Visible"] = TypeDescriptor.CreateProperty( typeof(MarqueeBorderDesigner), (PropertyDescriptor)properties["Visible"], new Attribute[0]); properties["Enabled"] = TypeDescriptor.CreateProperty( typeof(MarqueeBorderDesigner), (PropertyDescriptor)properties["Enabled"], new Attribute[0]);
5. Implement the Enabled and Visible properties. These implementations shadow the control's properties. C#
25 of 36
5/25/2012 11:39 AM
http://msdn.microsoft.com/en-us/library/35ea88wb
public bool Visible { get { return (bool)ShadowProperties["Visible"]; } set { this.ShadowProperties["Visible"] = value; } } public bool Enabled { get { return (bool)ShadowProperties["Enabled"]; } set { this.ShadowProperties["Enabled"] = value; } }
26 of 36
5/25/2012 11:39 AM
Walkthrough: Creating a Windows Forms Control That Takes Advantage ... IComponentChangeService cs = GetService(typeof(IComponentChangeService)) as IComponentChangeService;
http://msdn.microsoft.com/en-us/library/35ea88wb
2. Implement the OnComponentChanged event handler. Test the sending component's type, and if it is an IMarqueeWidget, call its Refresh method. C# private void OnComponentChanged( object sender, ComponentChangedEventArgs e) { if (e.Component is IMarqueeWidget) { this.Control.Refresh(); } }
27 of 36
5/25/2012 11:39 AM
Walkthrough: Creating a Windows Forms Control That Takes Advantage ... c.Start();
http://msdn.microsoft.com/en-us/library/35ea88wb
2. Connect these event handlers to their corresponding designer verbs. MarqueeControlRootDesigner inherits a DesignerVerbCollection from its base class. You will create two new DesignerVerb objects and add them to this collection in the Initialize method. C# this.Verbs.Add( new DesignerVerb("Run Test", new EventHandler(OnVerbRunTest)) ); this.Verbs.Add( new DesignerVerb("Stop Test", new EventHandler(OnVerbStopTest)) );
28 of 36
5/25/2012 11:39 AM
Walkthrough: Creating a Windows Forms Control That Takes Advantage ... internal class LightShapeEditor : UITypeEditor {
http://msdn.microsoft.com/en-us/library/35ea88wb
3. Declare an IWindowsFormsEditorService instance variable called editorService. C# private IWindowsFormsEditorService editorService = null;
4. Override the GetEditStyle method. This implementation returns DropDown, which tells the design environment how to display the LightShapeEditor. C# public override UITypeEditorEditStyle GetEditStyle( System.ComponentModel.ITypeDescriptorContext context) { return UITypeEditorEditStyle.DropDown; }
5. Override the EditValue method. This implementation queries the design environment for an IWindowsFormsEditorService object. If successful, it creates a LightShapeSelectionControl. The DropDownControl method is invoked to start the LightShapeEditor. The return value from this invocation is returned to the design environment. C# public override object EditValue( ITypeDescriptorContext context, IServiceProvider provider, object value) { if (provider != null) { editorService = provider.GetService( typeof(IWindowsFormsEditorService)) as IWindowsFormsEditorService; } if (editorService != null) { LightShapeSelectionControl selectionControl = new LightShapeSelectionControl( (MarqueeLightShape)value, editorService);
29 of 36
5/25/2012 11:39 AM
Walkthrough: Creating a Windows Forms Control That Takes Advantage ... editorService.DropDownControl(selectionControl); } } value = selectionControl.LightShape;
http://msdn.microsoft.com/en-us/library/35ea88wb
return value;
30 of 36
5/25/2012 11:39 AM
Walkthrough: Creating a Windows Forms Control That Takes Advantage ... this.editorService.CloseDropDown(); }
http://msdn.microsoft.com/en-us/library/35ea88wb
2. Declare an IWindowsFormsEditorService instance variable called editorService. C# private IWindowsFormsEditorService editorService; 1. Declare a MarqueeLightShape instance variable called lightShapeValue. C# private MarqueeLightShape lightShapeValue = MarqueeLightShape.Square;
2. In the LightShapeSelectionControl constructor, attach the Click event handlers to the squarePanel and circlePanel controls' Click events. Also, define a constructor overload that assigns the MarqueeLightShape value from the design environment to the lightShapeValue field. C# // This constructor takes a MarqueeLightShape value from the // design-time environment, which will be used to display // the initial state. public LightShapeSelectionControl( MarqueeLightShape lightShape, IWindowsFormsEditorService editorService ) { // This call is required by the designer. InitializeComponent(); // Cache the light shape value provided by the // design-time environment. this.lightShapeValue = lightShape; // Cache the reference to the editor service. this.editorService = editorService; // Handle the Click event for the two panels. this.squarePanel.Click += new EventHandler(squarePanel_Click); this.circlePanel.Click += new EventHandler(circlePanel_Click); }
31 of 36
5/25/2012 11:39 AM
Walkthrough: Creating a Windows Forms Control That Takes Advantage ... protected override void Dispose( bool disposing ) { if( disposing ) { // Be sure to unhook event handlers // to prevent "lapsed listener" leaks. this.squarePanel.Click -= new EventHandler(squarePanel_Click); this.circlePanel.Click -= new EventHandler(circlePanel_Click);
http://msdn.microsoft.com/en-us/library/35ea88wb
} base.Dispose( disposing );
4. In Solution Explorer, click the Show All Files button. Open the LightShapeSelectionControl.Designer.cs or LightShapeSelectionControl.Designer.vb file, and remove the default definition of the Dispose method. 5. Implement the LightShape property. C# // LightShape is the property for which this control provides // a custom user interface in the Properties window. public MarqueeLightShape LightShape { get { return this.lightShapeValue; } set {
6. Override the OnPaint method. This implementation will draw a filled square and circle. It will also highlight the selected value by drawing a border around one shape or the other. C# protected override void OnPaint(PaintEventArgs e)
32 of 36
5/25/2012 11:39 AM
http://msdn.microsoft.com/en-us/library/35ea88wb
{ // Draw a filled square in the client area of // the squarePanel control. gSquare.FillRectangle( Brushes.Red, 0, 0, this.squarePanel.Width, this.squarePanel.Height );
// If the Square option has been selected, draw a // border inside the squarePanel. if( this.lightShapeValue == MarqueeLightShape.Square ) { gSquare.DrawRectangle( Pens.Black, 0, 0, this.squarePanel.Width-1, this.squarePanel.Height-1); } // Draw a filled circle in the client area of // the circlePanel control. gCircle.Clear( this.circlePanel.BackColor ); gCircle.FillEllipse( Brushes.Blue, 0, 0, this.circlePanel.Width, this.circlePanel.Height ); // If the Circle option has been selected, draw a // border inside the circlePanel. if( this.lightShapeValue == MarqueeLightShape.Circle ) { gCircle.DrawRectangle( Pens.Black, 0, 0, this.circlePanel.Width-1, this.circlePanel.Height-1); } } }
33 of 36
5/25/2012 11:39 AM
http://msdn.microsoft.com/en-us/library/35ea88wb
At this point, you can build the MarqueeControlLibrary project. Test your implementation by creating a control that inherits from the MarqueeControl class and using it on a form.
1. Open DemoMarqueeControl in the Windows Forms Designer. This creates an instance of the DemoMarqueeControl type and displays it in an instance of the MarqueeControlRootDesigner type. 2. In the Toolbox, open the MarqueeControlLibrary Components tab. You will see the MarqueeBorder and MarqueeText controls available for selection. 3. Drag an instance of the MarqueeBorder control onto the DemoMarqueeControl design surface. Dock this MarqueeBorder control to the parent control. 4. Drag an instance of the MarqueeText control onto the DemoMarqueeControl design surface. 5. Build the solution. 6. Right-click the DemoMarqueeControl and from the shortcut menu select the Run Test option to start the animation. Click Stop Test to stop the animation. 7. Open Form1 in Design view. 8. Place two Button controls on the form. Name them startButton and stopButton, and change the Text property values to Start and Stop, respectively. 9. Implement Click event handlers for both Button controls. 10. In the Toolbox, open the MarqueeControlTest Components tab. You will see the DemoMarqueeControl available for selection. 11. Drag an instance of DemoMarqueeControl onto the Form1 design surface. 12. In the Click event handlers, invoke the Start and Stop methods on the DemoMarqueeControl. C# private void startButton_Click(object sender, System.EventArgs e) { this.demoMarqueeControl1.Start(); } private void stopButton_Click(object sender, System.EventArgs e) { this.demoMarqueeControl1.Stop(); } 1. Set the MarqueeControlTest project as the startup project and run it. You will see the form displaying your DemoMarqueeControl. Click the Start button to start the animation. You should see the text flashing and the lights moving around the border.
Next Steps
The MarqueeControlLibrary demonstrates a simple implementation of custom controls and
34 of 36
5/25/2012 11:39 AM
http://msdn.microsoft.com/en-us/library/35ea88wb
associated designers. You can make this sample more sophisticated in several ways: Change the property values for the DemoMarqueeControl in the designer. Add more MarqueBorder controls and dock them within their parent instances to create a nested effect. Experiment with different settings for the UpdatePeriod and the light-related properties. Author your own implementations of IMarqueeWidget. You could, for example, create a flashing "neon sign" or an animated sign with multiple images. Further customize the design-time experience. You could try shadowing more properties than Enabled and Visible, and you could add new properties. Add new designer verbs to simplify common tasks like docking child controls. License the MarqueeControl. For more information, see How to: License Components and Controls. Control how your controls are serialized and how code is generated for them. For more information, see Dynamic Source Code Generation and Compilation.
See Also
Tasks How to: Create a Windows Forms Control That Takes Advantage of Design-Time Features Reference UserControl ParentControlDesigner DocumentDesigner IRootDesigner DesignerVerb UITypeEditor BackgroundWorker Other Resources Extending Design-Time Support Custom Designers .NET Shape Library: A Sample Designer
Change History
Date
July 2010
History
Added a note about the .NET Framework Client Profile.
Reason
Customer feedback.
Yes
No
35 of 36
5/25/2012 11:39 AM
http://msdn.microsoft.com/en-us/library/35ea88wb
Community Content
system.design
at first this stumpped me for about 5 min if you right click on the second from top most item (which will be your first project you will have two) in your solution explorer and select properties, on the first tab on the left make sure Application is selected and then make sure Target Framework is set to .NET Framework 4 not .NET Framework 4 client profile same for 3.5 and etc.. no client profile then close this tab and do the same for the second project under your solution the system.design will be available now im stuck on another part 11/9/2011 Thomas Lee 8/30/2011 Donny101
36 of 36
5/25/2012 11:39 AM