首先,您需要将 AllowTransperency
设置为 True
。然后,您可以将窗口的背景设置为透明(到所需程度)的刷子:
<Window x:Class="MyWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
WindowStyle="None"
AllowsTransparency="True"
Background="{DynamicResource WindowBackground}">
<Window.Resources>
<SolidColorBrush x:Key="WindowBackground"
Color="White"
Opacity="0.5"/>
</Window.Resources>
...
</Window>
请注意,只有在将
WindowStyle
设置为
None
时,才能将
AllowTransperency
设置为
True
。
更新:
如果你不想将WindowStyle
设置为None
,并希望保留标准边框和窗口按钮,则有一种替代方法,该方法仅适用于具有Windows Aero主题的Windows Vista/7。
诀窍是使用以下代码将“Glass”区域扩展到整个窗口:
public static class WindowUtils
{
public static void ExtendGlass(this Window window, Thickness thikness) {
try {
int isGlassEnabled = 0;
Win32.DwmIsCompositionEnabled(ref isGlassEnabled);
if (Environment.OSVersion.Version.Major > 5 && isGlassEnabled > 0) {
var helper = new WindowInteropHelper(window);
var mainWindowSrc = HwndSource.FromHwnd(helper.Handle);
if (mainWindowSrc != null) {
if (mainWindowSrc.CompositionTarget != null) {
mainWindowSrc.CompositionTarget.BackgroundColor = Colors.Transparent;
}
System.Drawing.Graphics desktop =
System.Drawing.Graphics.FromHwnd(mainWindowSrc.Handle);
float dpiX = desktop.DpiX / 96;
float dpiY = desktop.DpiY / 96;
var margins = new MARGINS {
cxLeftWidth = (int)(thikness.Left * dpiX),
cxRightWidth = (int)(thikness.Right * dpiX),
cyBottomHeight = (int)(thikness.Bottom * dpiY),
cyTopHeight = (int)(thikness.Top * dpiY)
};
window.Background = Brushes.Transparent;
Win32.DwmExtendFrameIntoClientArea(mainWindowSrc.Handle, ref margins);
}
}
else {
window.Background = SystemColors.WindowBrush;
}
}
catch (DllNotFoundException) {
}
}
}
public class Win32
{
[DllImport("dwmapi.dll")]
public static extern int DwmExtendFrameIntoClientArea(IntPtr hWnd, ref MARGINS pMarInset);
[DllImport("dwmapi.dll")]
public static extern int DwmIsCompositionEnabled(ref int en);
[DllImport("user32.dll")]
public static extern bool SetCursorPos(int X, int Y);
[DllImport("User32", EntryPoint = "ClientToScreen", SetLastError = true, ExactSpelling = true, CharSet = CharSet.Auto)]
public static extern int ClientToScreen(IntPtr hWnd, [In, Out] POINT pt);
}
[StructLayout(LayoutKind.Sequential)]
public struct MARGINS
{
public int cxLeftWidth;
public int cxRightWidth;
public int cyTopHeight;
public int cyBottomHeight;
}
[StructLayout(LayoutKind.Sequential)]
public class POINT
{
public int x = 0;
public int y = 0;
}
为了将玻璃扩展到整个窗口,您需要在窗口的SizeChanged事件处理程序中调用ExtendGlass扩展方法,并传递完整覆盖窗口的Thickness
:
public MyWindow() {
InitializeComponent();
SizeChanged += OnSizeChanged;
}
private void OnSizeChanged(object sender, SizeChangedEventArgs e) {
double horisontalThickness = Width / 2;
double verticalThickness = Height / 2;
var glassThickness = new Thickness(horisontalThickness, verticalThickness, horisontalThickness, verticalThickness);
this.ExtendGlass(glassThickness);
}