using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Drawing;
using System.Drawing.Drawing2D;
namespace WindowsFormsApplication1
{
public class ControlExample : Control
{
private const int Alpha = 111;
public ControlExample()
{
this.SetStyle(System.Windows.Forms.ControlStyles.Opaque, true);
base.CreateControl();
}
protected override CreateParams CreateParams
{
get
{
CreateParams cp = base.CreateParams;
//开启 WS_EX_TRANSPARENT, 使控件支持透明
cp.ExStyle |= 0x00000020;
return cp;
}
}
protected override void OnPaint(PaintEventArgs e)
{
float width;
float height;
Pen srcPen;
SolidBrush srcBrush;
Color srcColor = Color.FromArgb(Alpha, this.BackColor);
srcPen = new Pen(srcColor, 0);
srcBrush = new SolidBrush(srcColor);
base.OnPaint(e);
width = this.Size.Width;
height = this.Size.Height;
e.Graphics.DrawRectangle(srcPen, 0, 0, width, height);
e.Graphics.FillRectangle(srcBrush, 0, 0, width, height);
e.Graphics.DrawString(this.Text, this.Font, new SolidBrush(Color.Black), new Rectangle(0, 0, this.Width, this.Height), new StringFormat() { Alignment = StringAlignment.Center, LineAlignment = StringAlignment.Center });
base.OnPaint(e);
}
}
}
WINFORM 自定义控件,类似做一个半透明的遮罩层。
就是在加载数据或是做一些比较耗时的操作,就显示这个控件,置于顶层,让用户点不到别的控件,防止误操作。
重写控件的ONPAINT事件来自己绘制UI。
在设置构造方法里设置控件样式 this.SetStyle(System.Windows.Forms.ControlStyles.Opaque, true); 时,可以绘制出透明的效果来,我可以在上面用 e.Graphics.DrawString 来画出我所要的提示信息出来,但是如果要动态提示程序的执行进度,就是这个绘制的字符串要动态去改变时,就要在设置这个TEXT的值后,再强制刷新UI。引发UI重绘事件。进入ONPAINT。
this.controlExampleTest.Text = "111111111111";
this.controlExampleTest.Invalidate();
这个是可以重绘UI,但是问题来了。在引发UI重绘后。画出来的UI。会造成,上一次的字符串依然还在,就是在原有的字符串上再画新的字符串。
如下图1(第一次ONPAINT的结果),图2(更新TEXT的值后,调用Invalidate方法时所出现的效果。) 所示:
图1:
图2:
我以我想怎么样才能在把原有的(上一次所画的字符串清掉),再重新画新的字符串上去。或是有什么别的解决办法。
现在我试过把 this.SetStyle(System.Windows.Forms.ControlStyles.Opaque, true); 去掉。
画出来的字符就不会是两次重桑的效果。
但是这个控件就不会是透明的了。看不到像图1和图2那样看得到在这个控件底层的控件了。(这个控件设置是置于顶层的。)
效果图如图3。
图3: