我根据 Microsoft.com 上的本教程组织了一个快速TransparencyConverter
课程,您可以将其用于此目的:
using System;
using System.Runtime.InteropServices;
using System.Windows;
using System.Windows.Interop;
namespace WpfApplication2
{
class TransparencyConverter
{
private readonly Window _window;
public TransparencyConverter(Window window)
{
_window = window;
}
public void MakeTransparent()
{
var mainWindowPtr = new WindowInteropHelper(_window).Handle;
var mainWindowSrc = HwndSource.FromHwnd(mainWindowPtr);
if (mainWindowSrc != null)
if (mainWindowSrc.CompositionTarget != null)
mainWindowSrc.CompositionTarget.BackgroundColor = System.Windows.Media.Color.FromArgb(0, 0, 0, 0);
var margins = new Margins
{
cxLeftWidth = 0,
cxRightWidth = Convert.ToInt32(_window.Width) * Convert.ToInt32(_window.Width),
cyTopHeight = 0,
cyBottomHeight = Convert.ToInt32(_window.Height) * Convert.ToInt32(_window.Height)
};
if (mainWindowSrc != null) DwmExtendFrameIntoClientArea(mainWindowSrc.Handle, ref margins);
}
[StructLayout(LayoutKind.Sequential)]
public struct Margins
{
public int cxLeftWidth;
public int cxRightWidth;
public int cyTopHeight;
public int cyBottomHeight;
}
[DllImport("DwmApi.dll")]
public static extern int DwmExtendFrameIntoClientArea(IntPtr hwnd, ref Margins pMarInset);
}
}
完成后,将透明背景属性添加到 XAML 并订阅 Window_Loaded 事件并调用 MakeTransparent 方法:
<Window etc etc Background="Transparent" Loaded="Window_Loaded">
private void Window_Loaded(object sender, RoutedEventArgs e)
{
var transparencyConverter = new TransparencyConverter(this);
transparencyConverter.MakeTransparent();
}
截图如下: