1、创建类库项目
在当前解决方案中添加新项目类库。
注意选择“.NET Framework”
创建完成后,删除默认的Class1类。
2、添加项目图片
在类库的debug中添加一个文件夹image,并复制项目需要的图片。
3、把全部项目拖放到资源文件中
选中所有图片,然后拖放到[资源],方法是右击类库项目,选择[属性]—>[资源]—>单击创建链接。
选中images里面所有图片,拖放到右边,即可添加到Resources资源文件中:
4、添加用户控件
右击类库项目名称,选择[添加]—>[新建项]然后再窗口中选择“用户控件(Windows窗体)”。
然后单击添加按钮,可以看到用户控件的模板:
5、设置尺寸样式
6、按F7进入代码视图
编写如下代码:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace thing.HeatingCustomControls
{
public partial class ThingerHCValve : UserControl
{
public ThingerHCValve()
{
InitializeComponent();
}
private bool isRun;
[Category("自定义属性")]
[Description("阀门启动或关闭")]
public bool IsRun
{
get
{
return isRun;
}
set
{
if(value != isRun)
{
isRun = value;
if (isRun)
{
this.lblValve.Text = "已打开";
this.picValve.BackgroundImage = Properties.Resources.阀门Open;
}
else
{
this.lblValve.Text = "已关闭";
this.picValve.BackgroundImage = Properties.Resources.阀门Close;
}
}
}
}
public event Action<bool> IsRunChanged;
[Category("自定义事件")]
[Description("阀门双击事件")]
private void picValve_DoubleClick(object sender, EventArgs e)
{
if(IsRunChanged == null)
{
IsRunChanged(IsRun);
}
}
}
}
设置样式属性减少控件使用时的闪烁
this.SetStyle(ControlStyles.UserPaint, true);
this.SetStyle(ControlStyles.AllPaintingInWmPaint, true);
this.SetStyle(ControlStyles.DoubleBuffer, true);
this.SetStyle(ControlStyles.ResizeRedraw, true);
this.SetStyle(ControlStyles.Selectable, true);
this.SetStyle(ControlStyles.SupportsTransparentBackColor, true);
AllPaintingInWmPaint | 8192 | 如果为 |
CacheText | 16384 | 如果为 |
ContainerControl | 1 | 如果为 |
DoubleBuffer | 65536 | 如果为 |
EnableNotifyMessage | 32768 | 如果为 |
FixedHeight | 64 | 如果为 |
FixedWidth | 32 | 如果为 |
Opaque | 4 | 如果为 |
OptimizedDoubleBuffer | 131072 | 如果为 |
ResizeRedraw | 16 | 如果为 |
Selectable | 512 | 如果为 |
StandardClick | 256 | 如果为 |
StandardDoubleClick | 4096 | 如果为 |
SupportsTransparentBackColor | 2048 | 如果为 |
UserMouse | 1024 | 如果为 |
UserPaint | 2 | 如果为 |
UseTextForAccessibility | 262144 | 指定控件的 |