因为winform Form窗体的局限性,不允许设置背景色为transparent。所以不能实现透明背景。这里有一个取巧的方法,通过截取窗口后的的背景来实现背景透明效果。
先把代码贴上来:
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 ElectronicPlanning { public partial class Form1 : Form { private Color tr_color = Color.Transparent; private bool b_start = false; bool[] b_visible = null; public Form1() { InitializeComponent(); } private void Form1_Load(object sender, EventArgs e) { SetBackgroundImageTransparent(); } private void SetBackgroundImageTransparent() { Point pt = this.PointToScreen(new Point(0, 0)); Bitmap b = new Bitmap(this.Width, this.Height); using (Graphics g = Graphics.FromImage(b)) { g.CopyFromScreen(pt, new Point(), new Size(this.Width, this.Height)); } this.BackgroundImage = b; } private void BeginSet() { tr_color = this.TransparencyKey; b_start = true; } private void Setting() { if (b_start) { b_visible = new bool[Controls.Count]; for (int i = 0; i < Controls.Count; i++) { b_visible[i] = Controls[i].Visible; Controls[i].Visible = false; } BackgroundImage = null; BackColor = Color.White; b_start = false; this.TransparencyKey = Color.White; } } private void EndSet() { SetBackgroundImageTransparent(); this.TransparencyKey = tr_color; for (int i = 0; i < Controls.Count; i++) { Controls[i].Visible = b_visible[i]; } b_start = false; } private void Form1_Resize(object sender, EventArgs e) { Setting(); } private void Form1_ResizeBegin(object sender, EventArgs e) { BeginSet(); } private void Form1_ResizeEnd(object sender, EventArgs e) { EndSet(); } private void Form1_Move(object sender, EventArgs e) { Setting(); } } }
如果想设置为半透明的效果,就添加一个panel,然后把panel的背景设置为透明,再添加一张半透明的图片即可实现半透明的遮罩图片,即可实现效果。本文来自于广州地理信息网:http://www.gzgis.com
全透明效果如下: