winform窗体透明背景实现

因为winform Form窗体的局限性,不允许设置背景色为transparent。所以不能实现透明背景。
这里有一个取巧的方法(截Form后的背景)。
首先来看下实现效果:
681225147.png
想要实现半透明效果只要加个panel ,将panel设置为背景色透明,然后加个遮罩图片就可以了。
650303991.png

以下附上实现代码:

using System;
using System.Drawing;
using System.Windows.Forms;

namespace WindowsTrans
{
    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();
        }
    }
}
© 版权声明
THE END
喜欢就支持一下吧
点赞0 分享
评论 抢沙发
头像
欢迎您留下宝贵的见解!
提交
头像

昵称

取消
昵称表情代码图片

    暂无评论内容