C#繼承Control實用自定義控件


start
步驟一:新建類庫項目,新建FirstControl.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

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

namespace UcDll
{
     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);

        }
    }
}
步驟二:編譯,添加項目引用即可。
這里的重點是控件界面也要由自己繪。
url: http://greatverve.cnblogs.com/archive/2012/04/27/control-Inherit.html
參考:
http://www.cnblogs.com/guanjinke/category/77694.html
http://blog.csdn.net/yysyangyangyangshan/article/details/7078471


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM