Winform自定义控件

来源:互联网 发布:淘宝找回密码支付宝 编辑:程序博客网 时间:2024/05/17 04:32

Winform控件分为用户控件和自定义控件,用户控件比较简单,本文讨论的是自定义控件。

MS控件,无论是Winform控件还是Webform控件,无论是用户控件还是自定义控件,都有着相同的设计思想。

1)对于自定义控件来说:

Winform控件的UI显示是靠OnPrint方法,Webform控件的UI显示是靠RenderXXXX方法。

2)对于自定义控件和用户控件来说:

Winfrom控件和Webform控件的属性在UI设计中起到了至关重要的作用。在设计视图中都可以设置属性来达到设置UI的效果。记得Winfrom的属性set要调用Invalidate();方法来完成重绘。

3)对于设计UI来说:

Winform是依赖于GDI+绘制,Webform则依赖对html的熟悉,通过render将生成的html代码返回到客户端。

以下是Winfrom自定义控件的代码:

 using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;

namespace WinformControl
{
    
public partial class LandpyControl : Control
    {
        
public LandpyControl()
        {
            InitializeComponent();
        }

        
private Color _textColor;

        
public Color TextColor
        {
            
get { return _textColor; }
            
set
            {
                _textColor 
= value;
                Invalidate();
            }
        }

        
protected override void OnPaint(PaintEventArgs pe)
        {
            
base.OnPaint(pe);
            Font enFont 
= new Font("Times New Roman"12);
            Rectangle rect 
= pe.ClipRectangle;
            pe.Graphics.DrawString(Text, enFont, 
new SolidBrush(_textColor), 00);
        }

        
protected override void OnClick(EventArgs e)
        {
            
base.OnClick(e);
            _textColor 
= Color.Red;
            Invalidate();
        }

        
protected override void OnMouseLeave(EventArgs e)
        {
            
base.OnMouseLeave(e);
            _textColor 
= Color.Black;
            Invalidate();
        }
    }
}

通过TextColor可以设置显示文字的颜色,并且可定义控件的事件。

简单的Winfrom自定义控件就完成了。

原创粉丝点击