1500字范文,内容丰富有趣,写作好帮手!
1500字范文 > C# 窗体半透明 控件不透明

C# 窗体半透明 控件不透明

时间:2022-09-17 01:44:49

相关推荐

C# 窗体半透明 控件不透明

效果:

采用两层窗体实现

上方窗体,背景全透明,控件不透明,鼠标可穿透下方窗体,通过Opacity调整透明度,无控件,鼠标不可穿透

前景窗体:

using System;using System.Collections.Generic;using System.Drawing;using System.Linq;using System.Runtime.InteropServices;using System.Text;using System.Windows.Forms;namespace WindowsFormsApp26{class FrmForeground:Form{public FrmForeground(){InitUI();this.Load += FrmTransparent_Load;}private void InitUI(){Label lab = new Label(); //要显示的文本lab.AutoSize = true;lab.Text = "我是在半透明窗体上";lab.BackColor = Color.Transparent; //背景色透明lab.Location = new Point(90, 150); //调整在窗体上的位置this.Controls.Add(lab);this.FormBorderStyle = FormBorderStyle.None;}private void FrmTransparent_Load(object sender, EventArgs e){// 设置背景全透明this.BackColor = Color.AliceBlue;this.TransparencyKey = Color.AliceBlue;// 设置窗体鼠标穿透SetPenetrate();}#region win32 apiprivate const uint WS_EX_LAYERED = 0x80000;private const int WS_EX_TRANSPARENT = 0x20;private const int GWL_STYLE = (-16);private const int GWL_EXSTYLE = (-20);private const int LWA_ALPHA = 0;[DllImport("user32", EntryPoint = "SetWindowLong")]private static extern uint SetWindowLong(IntPtr hwnd,int nIndex,uint dwNewLong);[DllImport("user32", EntryPoint = "GetWindowLong")]private static extern uint GetWindowLong(IntPtr hwnd,int nIndex);[DllImport("user32", EntryPoint = "SetLayeredWindowAttributes")]private static extern int SetLayeredWindowAttributes(IntPtr hwnd,int crKey,int bAlpha,int dwFlags);#endregion/// <summary> /// 设置窗体具有鼠标穿透效果 /// </summary> public void SetPenetrate(){GetWindowLong(this.Handle, GWL_EXSTYLE);SetWindowLong(this.Handle, GWL_EXSTYLE, WS_EX_TRANSPARENT | WS_EX_LAYERED);}}}

背景窗体:

using System;using System.Collections.Generic;using System.Drawing;using System.Linq;using System.Text;using System.Windows.Forms;namespace WindowsFormsApp26{class FrmBackgound{public static void Show(Form frmTop, Form frmBackOwner, Color frmBackColor, double frmBackOpacity){// 背景窗体设置var frmBack = new Form();frmBack.FormBorderStyle = FormBorderStyle.None;frmBack.StartPosition = FormStartPosition.Manual;frmBack.ShowIcon = false;frmBack.ShowInTaskbar = false;frmBack.Opacity = frmBackOpacity;frmBack.BackColor = frmBackColor;frmBack.Owner = frmBackOwner;frmBack.Size = frmTop.Size;frmBack.Location = frmTop.Location;// 顶部窗体设置frmTop.Owner = frmBack;frmTop.StartPosition = FormStartPosition.Manual;frmTop.LocationChanged += (o, args) => { frmBack.Location = frmTop.Location; };// 显示窗体frmTop.Show();frmBack.Show();}}}

调用:

private void button1_Click(object sender, EventArgs e){var frmForeground = new FrmForeground();frmForeground.Location = new System.Drawing.Point(50,50);FrmBackgound.Show(frmForeground, this, Color.Yellow, 0.8);}

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。