今天学习了自定义控件,通过查资料实现了流速条自定义控件,现记录如下:
第一步:新建项目,创建windows窗体控件库;
第二步:书写程序;
本次创建的控件继承自UserControl类;
最终效果如图:
具体代码:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Drawing.Drawing2D;
namespace LiuSuTiao
{
public partial class LiuSuTiao : UserControl
{
public LiuSuTiao()
{
InitializeComponent();
//设置绘制对象的相应属性
this.SetStyle(ControlStyles.UserPaint, true);//由控件而非操作系统绘制自身
this.SetStyle(ControlStyles.AllPaintingInWmPaint, true);//如果为true,则忽略窗口消息wm_erasebkgnd以减少闪烁
//this.SetStyle(ControlStyles.OptimizedDoubleBuffer, true);//控件首先绘制到缓冲区而非直接绘制到屏幕
this.SetStyle(ControlStyles.DoubleBuffer, true);//控件首先绘制到缓冲区,完成后将结果绘制到屏幕
this.SetStyle(ControlStyles.ResizeRedraw, true);//控件在调整大小时进行重绘
this.SetStyle(ControlStyles.Selectable, true);
this.SetStyle(ControlStyles.SupportsTransparentBackColor, true);
Timer MyTimer = new Timer();//按用户定义的时间间隔触犯事件
MyTimer.Enabled = true;
MyTimer.Interval = 1000;//1秒
MyTimer.Tick += MyTimer_Tick;
}
private void MyTimer_Tick(object sender, EventArgs e)
{
//throw new NotImplementedException();
this.Invalidate();//使控件的整个图面无效,并重绘控件
}
#region 定义图面、宽度及高度
private Graphics g;
private int pic_width;
private int pic_heigt;
#endregion
private bool active;
[Description("控件是否激活,即流速条是否启动"), Category("自定义属性")]
public bool Active
{
get
{
return active;
}
set
{
active = value;
}
}
bool vertical = false;
[Description("外部矩形方向"), Category("自定义属性")]
public bool Vertical
{
get { return vertical; }
set { vertical = value; }
}
int neibujuxing_length = 10;
[Description("内部矩形长度"), Category("自定义属性")]
public int Neibujuxing_Length
{
get { return neibujuxing_length; }
set { neibujuxing_length = value; }
}
double neibujuxing_width = 0.75;