效果:
采用两层窗体实现
- 上方窗体,背景全透明,控件不透明,鼠标可穿透
- 下方窗体,通过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 api
private 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);
}