winform窗体透明背景实现

根目录
2021-12-25 / 0 评论 / 71 阅读 / 正在检测是否收录...

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

以下附上实现代码:

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();
        }
    }
}
本文共 93 个字数,平均阅读时长 ≈ 1分钟
0

打赏

海报

正在生成.....

评论 (0)

取消