因为winform Form窗体的局限性,不允许设置背景色为transparent。所以不能实现透明背景。
这里有一个取巧的方法(截Form后的背景)。
首先来看下实现效果:
想要实现半透明效果只要加个panel ,将panel设置为背景色透明,然后加个遮罩图片就可以了。
以下附上实现代码:
1 using System; 2 using System.Drawing; 3 using System.Windows.Forms; 4 5 namespace WindowsTrans 6 { 7 public partial class Form1 : Form 8 { 9 private Color tr_color = Color.Transparent; 10 private bool b_start = false; 11 bool[] b_visible = null; 12 public Form1() 13 { 14 InitializeComponent(); 15 } 16 private void Form1_Load(object sender, EventArgs e) 17 { 18 SetBackgroundImageTransparent(); 19 } 20 private void SetBackgroundImageTransparent() 21 { 22 Point pt = this.PointToScreen(new Point(0, 0)); 23 Bitmap b = new Bitmap(this.Width, this.Height); 24 using (Graphics g = Graphics.FromImage(b)) 25 { 26 g.CopyFromScreen(pt, new Point(), new Size(this.Width, this.Height)); 27 } 28 29 this.BackgroundImage = b; 30 } 31 private void BeginSet() 32 { 33 tr_color = this.TransparencyKey; 34 b_start = true; 35 } 36 private void Setting() 37 { 38 if (b_start) 39 { 40 b_visible = new bool[Controls.Count]; 41 for (int i = 0; i < Controls.Count; i++) 42 { 43 b_visible[i] = Controls[i].Visible; 44 Controls[i].Visible = false; 45 } 46 BackgroundImage = null; 47 BackColor = Color.White; 48 b_start = false; 49 this.TransparencyKey = Color.White; 50 } 51 } 52 private void EndSet() 53 { 54 SetBackgroundImageTransparent(); 55 this.TransparencyKey = tr_color; 56 for (int i = 0; i < Controls.Count; i++) 57 { 58 Controls[i].Visible = b_visible[i]; 59 } 60 b_start = false; 61 } 62 63 private void Form1_Resize(object sender, EventArgs e) 64 { 65 Setting(); 66 } 67 private void Form1_ResizeBegin(object sender, EventArgs e) 68 { 69 BeginSet(); 70 } 71 private void Form1_ResizeEnd(object sender, EventArgs e) 72 { 73 EndSet(); 74 } 75 private void Form1_Move(object sender, EventArgs e) 76 { 77 Setting(); 78 } 79 } 80 }