如何在WinUI3中实现窗口背景透明?
WinUI3实现窗口背景透明(保留内容可见、去除黑色边框)
WinUI3确实没有WPF里AllowTransparency="true"那样的直接设置,得结合Win32 API和XAML配置来实现,以下是具体步骤:
1. 配置XAML,确保内容背景透明
在窗口的XAML代码中,把窗口本身和根容器的背景都设为透明,避免默认背景遮挡:
<Window x:Class="YourAppNamespace.MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Background="Transparent"> <Grid Background="Transparent"> <!-- 这里放你的业务内容,比如文本、按钮等,内容会正常显示 --> <TextBlock Text="透明窗口中的可见内容" Foreground="Black" FontSize="28" HorizontalAlignment="Center" VerticalAlignment="Center"/> </Grid> </Window>
2. 添加Win32 API调用,设置窗口样式与分层属性
WinUI3基于Win32,需要通过API修改窗口样式,去除边框并设置分层透明:
首先,安装Microsoft.Windows.CsWin32 NuGet包,简化Win32 API的调用。
然后在窗口的后台代码(MainWindow.xaml.cs)中添加以下逻辑:
using Microsoft.UI.Xaml; using Windows.Win32; using Windows.Win32.Foundation; using Windows.Win32.UI.WindowsAndMessaging; namespace YourAppNamespace { public sealed partial class MainWindow : Window { public MainWindow() { this.InitializeComponent(); SetTransparentWindowStyle(); } private void SetTransparentWindowStyle() { // 获取当前窗口的HWND HWND hwnd = WinRT.Interop.WindowNative.GetWindowHandle(this); // 移除窗口的标题栏和边框样式 int windowStyle = PInvoke.GetWindowLongW(hwnd, WINDOW_LONG_PTR_INDEX.GWL_STYLE); windowStyle &= ~(int)WINDOW_STYLE.WS_CAPTION; windowStyle &= ~(int)WINDOW_STYLE.WS_THICKFRAME; PInvoke.SetWindowLongW(hwnd, WINDOW_LONG_PTR_INDEX.GWL_STYLE, windowStyle); // 添加分层窗口扩展样式(实现透明的关键) int exWindowStyle = PInvoke.GetWindowLongW(hwnd, WINDOW_LONG_PTR_INDEX.GWL_EXSTYLE); exWindowStyle |= (int)WINDOW_EX_STYLE.WS_EX_LAYERED; PInvoke.SetWindowLongW(hwnd, WINDOW_LONG_PTR_INDEX.GWL_EXSTYLE, exWindowStyle); // 设置窗口整体不透明(我们只需要背景透明,内容正常显示) PInvoke.SetLayeredWindowAttributes(hwnd, 0, 255, LAYERED_WINDOW_ATTRIBUTES_FLAGS.LWA_ALPHA); // 刷新窗口样式 PInvoke.SetWindowPos(hwnd, HWND.Null, 0, 0, 0, 0, SET_WINDOW_POS_FLAGS.SWP_FRAMECHANGED | SET_WINDOW_POS_FLAGS.SWP_NOMOVE | SET_WINDOW_POS_FLAGS.SWP_NOSIZE); } } }
3. 配置应用权限(针对MSIX打包应用)
如果你的应用是用MSIX打包的,需要在Package.appxmanifest中添加全信任权限,否则无法调用Win32 API:
<Package ... xmlns:rescap="http://schemas.microsoft.com/appx/manifest/foundation/windows10/restrictedcapabilities" IgnorableNamespaces="uap mp rescap"> ... <Capabilities> <rescap:Capability Name="runFullTrust"/> </Capabilities> </Package>
这样设置后,窗口的背景就会完全透明,内容保持可见,同时默认的黑色边框也会被移除。
内容的提问来源于stack exchange,提问作者Niilo Poutanen
相关产品推荐
相关产品推荐

