在Web上面要实现一个遮罩层或者说是蒙版吧,有了DIV那不算什么难事,只要给div定好位置和大小,把颜色的Alpha值设一下就有透明的效果。不过在Winform中实现起来就没那么简单了事。尝试过用一个Panel,那底色设成透明,真的透明了。窗体后面的东西都显示出来了。就是没把Panel盖住的控件显示出来。这样看来不是办法。谷了一会儿歌。找到了一个,还是要写控件的,不算难,但用到了一点儿没见过的东西。经一事长一智吧。
重写到了一个Control的属性CreateParams,它是CreateParams类型的。关于这个类,MSDN上简单解释道:封装创建控件时所需的信息。而依我看是关于样式的设置,而且里面的样式设置都是些0x00000040、0x00000020的按位组合。在网上找了一些,整理了了一下也塞到博文的最后面。
1 protected override CreateParams CreateParams 2 { 3 get 4 { 5 CreateParams cp = base.CreateParams; 6 cp.ExStyle |= 0x00000020; 7 return cp; 8 } 9 }
这样写控件下去,多半是要去重绘的,这里重写OnPaint方法不过不复杂,给控件填背景色,还是直接把所有代码贴出来。
1 public class MaskLayer:Control 2 { 3 private int alpha; 4 5 public MaskLayer() 6 { 7 alpha = 125; 8 SetStyle(System.Windows.Forms.ControlStyles.Opaque, true); 9 base.CreateControl(); 10 } 11 12 protected override void OnPaint(PaintEventArgs e) 13 { 14 15 base.OnPaint(e); 16 Color color = Color.FromArgb(alpha, this.BackColor); 17 using (SolidBrush brush = new SolidBrush(color)) 18 { 19 e.Graphics.FillRectangle(brush, 0, 0, this.Size.Width, this.Size.Height); 20 } 21 if (!this.DesignMode) 22 { 23 using (Pen pen = new Pen(color)) 24 { 25 e.Graphics.DrawRectangle(pen, 0, 0, this.Width, this.Height); 26 } 27 } 28 else 29 e.Graphics.DrawRectangle(Pens.Black, 1, 1, this.Width - 2, this.Height - 2); 30 } 31 32 protected override CreateParams CreateParams 33 { 34 get 35 { 36 Crea