代码改变世界

How to: Develop a Simple Windows Forms Control(转载)

2011-06-10 09:22  Dirichlet  阅读(285)  评论(0编辑  收藏  举报

转自: http://msdn.microsoft.com/en-us/library/649xahhe(VS.80).aspx

This section walks you through the key steps for authoring a custom Windows Forms control. The simple control developed in this walkthrough allows the alignment of its Text property to be changed. It does not raise or handle events.

To create a simple custom control

  1. Define a class that derives from System.Windows.Forms.Control.

     
    Public Class FirstControl
       Inherits Control
       
    End Class
    

     

     

     
    public class FirstControl:Control{}
    
  2. Define properties. (You are not required to define properties, because a control inherits many properties from the Control class, but most custom controls generally do define additional properties.) The following code fragment defines a property named TextAlignment thatFirstControl uses to format the display of the Text property inherited from Control. For more information about defining properties, see Properties Overview.

     
    // ContentAlignment is an enumeration defined in the System.Drawing
    // namespace that specifies the alignment of content on a drawing 
    // surface.
    private ContentAlignment alignmentValue = ContentAlignment.MiddleLeft;
    
    

    When you set a property that changes the visual display of the control, you must invoke the Invalidate method to redraw the control. Invalidateis defined in the base class Control.

  3. Override the protected OnPaint method inherited from Control to provide rendering logic to your control. If you do not override OnPaint, your control will not be able to draw itself. In the following code fragment, the OnPaint method displays the Text property inherited from Controlwith the alignment specified by the alignmentValue field.

     
    protected override void OnPaint(PaintEventArgs e) 
    {   
        base.OnPaint(e);
        StringFormat style = new StringFormat();
        style.Alignment = StringAlignment.Near;
        switch (alignmentValue) 
        {
            case ContentAlignment.MiddleLeft:
                style.Alignment = StringAlignment.Near;
                break;
            case ContentAlignment.MiddleRight:
                style.Alignment = StringAlignment.Far;
                break;
            case ContentAlignment.MiddleCenter:
                style.Alignment = StringAlignment.Center;
                break;
        }
        
        // Call the DrawString method of the System.Drawing class to write   
        // text. Text and ClientRectangle are properties inherited from
        // Control.
        e.Graphics.DrawString(
            Text, 
            Font, 
            new SolidBrush(ForeColor), 
            ClientRectangle, style);
    
    } 
    
    
  4. Provide attributes for your control. Attributes enable a visual designer to display your control and its properties and events appropriately at design time. The following code fragment applies attributes to the TextAlignment property. In a designer such as Visual Studio, the Categoryattribute (shown in the code fragment) causes the property to be displayed under a logical category. The Description attribute causes a descriptive string to be displayed at the bottom of the Properties window when the TextAlignment property is selected. For more information about attributes, see Design-Time Attributes for Components.

     
    [
    Category("Alignment"),
    Description("Specifies the alignment of text.")
    ]
    
    
  5. (optional) Provide resources for your control. You can provide a resource, such as a bitmap, for your control by using a compiler option (/res for C#) to package resources with your control. At run time, the resource can be retrieved using the methods of the ResourceManager class. For more information about creating and using resources, see the Resources in Applications.

  6. Compile and deploy your control. To compile and deploy FirstControl, execute the following steps:

    1. Save the code in the following sample to a source file (such as FirstControl.cs or FirstControl.vb).

    2. Compile the source code into an assembly and save it in your application's directory. To accomplish this, execute the following command from the directory that contains the source file.

       
      vbc /t:library /out:[path to your application's directory]/CustomWinControls.dll /r:System.dll /r:System.Windows.Forms.dll /r:System.Drawing.dll FirstControl.vb
      

       

       

       
      csc /t:library /out:[path to your application's directory]/CustomWinControls.dll /r:System.dll /r:System.Windows.Forms.dll /r:System.Drawing.dll FirstControl.cs
      

      The /t:library compiler option tells the compiler that the assembly you are creating is a library (and not an executable). The /out option specifies the path and name of the assembly. The/r option provides the name of the assemblies that are referenced by your code. In this example, you create a private assembly that only your applications can use. Hence, you have to save it in your application's directory. For more information about packaging and deploying a control for distribution, see Deploying .NET Framework Applications.

The following sample shows the code for FirstControl. The control is enclosed in the namespace CustomWinControls. A namespace provides a logical grouping of related types. You can create your control in a new or existing namespace. In C#, the using declaration (in Visual Basic, Imports) allows types to be accessed from a namespace without using the fully qualified name of the type. In the following example, the using declaration allows code to access the class Control from System.Windows.Forms as simply Control instead of having to use the fully qualified name System.Windows.Forms.Control.

 
using System;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;

namespace CustomWinControls
{
    public class FirstControl : Control
    {

        public FirstControl()
        {

        }

        // ContentAlignment is an enumeration defined in the System.Drawing
        // namespace that specifies the alignment of content on a drawing 
        // surface.
        private ContentAlignment alignmentValue = ContentAlignment.MiddleLeft;

        [
        Category("Alignment"),
        Description("Specifies the alignment of text.")
        ]
        public ContentAlignment TextAlignment 
        {
            
            get 
            {
                return alignmentValue;
            }
            set 
            {
                alignmentValue = value;

                // The Invalidate method invokes the OnPaint method described 
                // in step 3.
                Invalidate(); 
            }
        }
        

        protected override void OnPaint(PaintEventArgs e) 
        {   
            base.OnPaint(e);
            StringFormat style = new StringFormat();
            style.Alignment = StringAlignment.Near;
            switch (alignmentValue) 
            {
                case ContentAlignment.MiddleLeft:
                    style.Alignment = StringAlignment.Near;
                    break;
                case ContentAlignment.MiddleRight:
                    style.Alignment = StringAlignment.Far;
                    break;
                case ContentAlignment.MiddleCenter:
                    style.Alignment = StringAlignment.Center;
                    break;
            }
            
            // Call the DrawString method of the System.Drawing class to write   
            // text. Text and ClientRectangle are properties inherited from
            // Control.
            e.Graphics.DrawString(
                Text, 
                Font, 
                new SolidBrush(ForeColor), 
                ClientRectangle, style);

        } 
    }
}

Using the Custom Control on a Form

The following example shows a simple form that uses FirstControl. It creates three instances of FirstControl, each with a different value for the TextAlignment property.

To compile and run this sample

  1. Save the code in the following example to a source file (SimpleForm.cs or SimpleForms.vb).

  2. Compile the source code into an executable assembly by executing the following command from the directory that contains the source file.

     
    vbc /r:CustomWinControls.dll /r:System.dll /r:System.Windows.Forms.dll /r:System.Drawing.dll SimpleForm.vb
    

     

     

     
    csc /r:CustomWinControls.dll /r:System.dll /r:System.Windows.Forms.dll /r:System.Drawing.dll SimpleForm.cs
    

    CustomWinControls.dll is the assembly that contains the class FirstControl. This assembly must be in the same directory as the source file for the form that accesses it (SimpleForm.cs or SimpleForms.vb).

  3. Execute SimpleForm.exe using the following command.

     
     
    SimpleForm
    
 
using System;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;

namespace CustomWinControls
{
    public class FirstControl : Control
    {

        public FirstControl()
        {

        }

        // ContentAlignment is an enumeration defined in the System.Drawing
        // namespace that specifies the alignment of content on a drawing 
        // surface.
        private ContentAlignment alignmentValue = ContentAlignment.MiddleLeft;

        [
        Category("Alignment"),
        Description("Specifies the alignment of text.")
        ]
        public ContentAlignment TextAlignment 
        {
            
            get 
            {
                return alignmentValue;
            }
            set 
            {
                alignmentValue = value;

                // The Invalidate method invokes the OnPaint method described 
                // in step 3.
                Invalidate(); 
            }
        }
        

        protected override void OnPaint(PaintEventArgs e) 
        {   
            base.OnPaint(e);
            StringFormat style = new StringFormat();
            style.Alignment = StringAlignment.Near;
            switch (alignmentValue) 
            {
                case ContentAlignment.MiddleLeft:
                    style.Alignment = StringAlignment.Near;
                    break;
                case ContentAlignment.MiddleRight:
                    style.Alignment = StringAlignment.Far;
                    break;
                case ContentAlignment.MiddleCenter:
                    style.Alignment = StringAlignment.Center;
                    break;
            }
            
            // Call the DrawString method of the System.Drawing class to write   
            // text. Text and ClientRectangle are properties inherited from
            // Control.
            e.Graphics.DrawString(
                Text, 
                Font, 
                new SolidBrush(ForeColor), 
                ClientRectangle, style);

        } 
    }
}

See Also