【Winform-自定义控件】自定义控件学习+一个笑脸控件例子

1.CompositeControls组合控件:在原有控件的基础上根据需要进行组合

 

2.ExtendedControls 扩展控件:继承自原有控件,添加一些新的属性和方法,绘制一些新元素

当每个Button都使用一样的样式,可以使用自定义控件统一设置控件的属性、方法。

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

public class TouchscreenButton : Button
{
    public TouchscreenButton()
    {
        this.Width = 100;
        this.Height = 75;
        this.FlatStyle = FlatStyle.Flat;
        this.Cursor = Cursors.Hand;
        this.ForeColor = Color.Black;
        this.BackColor = Color.White;
        this.FlatAppearance.BorderSize = 2;
        this.FlatAppearance.BorderColor = Color.Navy;
    }
}

3.CustomControls自定义控件:控件的绘制全部由用户定义

一个可爱的笑脸控件

    public partial class Smiley : Control
    {

        public enum SampleColours
        {
            Red,
            Green,
            Blue,
            Yellow
        }
        //创建一个枚举类型的属性,则这个属性可以进行选择
        private SampleColours _smileyColor; 
        public SampleColours SmileyColor
        {
            get { return _smileyColor; }
            set { _smileyColor = value; }
        }

        private string _smileyName;
        public string SmileyName
        {
            get { return _smileyName; }
            set { _smileyName = value; }
        }

        public Smiley()
        {
            InitializeComponent();
        }

        protected override void OnPaint(PaintEventArgs pe)
        {
            //选择背景颜色
            Color back;
            switch (_smileyColor)
            {
                case SampleColours.Blue:
                    back = Color.Blue;
                    break;
                case SampleColours.Green:
                    back = Color.Green;
                    break;
                case SampleColours.Red:
                    back = Color.Red;
                    break;
                default:
                    back = Color.Yellow;
                    break;
            }
            Brush background = new SolidBrush(back);

            //画背景
            pe.Graphics.FillEllipse(background, 0, 0, this.Width - 1, this.Height - 1);
            //左眼
            pe.Graphics.FillEllipse(Brushes.Black, (this.Width / 4), (this.Height / 4), (this.Width / 6), (this.Height / 6));
            //右眼
            pe.Graphics.FillEllipse(Brushes.Black, this.Width - (this.Width / 3) - 10, (this.Height / 4), (this.Width / 6), (this.Height / 6));
            //
            pe.Graphics.DrawArc(Pens.Black, (this.Width / 4), (this.Height / 2), (this.Width / 2), (this.Height / 4), 0, 180);

            // Calling the base class OnPaint
            base.OnPaint(pe);
        }
    }

 

posted @ 2017-04-24 17:00  发明创造小能手  阅读(303)  评论(0编辑  收藏  举报
levels of contents