分层(透明)WPF 窗口中的 Win32 本机控件不可见



我想在WPF窗口中托管一个本机Win32(Qt小部件(控件。我的问题是,如果我在普通的 WPF 窗口中托管它,一切正常,但是当我将 WPF 窗口的AllowsTransparency设置为 true 时,本机内容将不再呈现。我做了一个简单的测试应用程序,它只创建一个Win32按钮,看看Qt是否是罪魁祸首,但事实并非如此。

这是我拥有的HwndHost实现:

using System;
using System.Runtime.InteropServices;
using System.Windows.Interop;
namespace WpfHwndHostLayeredWindow
{
    class NativeButton : HwndHost
    {
        protected override HandleRef BuildWindowCore(HandleRef hwndParent)
        {
            var hwnd = PInvoke.User32.CreateWindowEx(
                0, // EX_STYLE
                "BUTTON",
                "Win32 Button",
                PInvoke.User32.WindowStyles.WS_CHILD,
                0, 0, 100, 100,
                hwndParent.Handle,
                IntPtr.Zero, // hMenu
                new IntPtr(PInvoke.User32.GetWindowLong(hwndParent.Handle, PInvoke.User32.WindowLongIndexFlags.GWLP_HINSTANCE)),
                IntPtr.Zero // lParam
            );
            return new HandleRef(this, hwnd);
        }
        protected override void DestroyWindowCore(HandleRef hwnd)
        {
            PInvoke.User32.DestroyWindow(hwnd.Handle);
        }
    }
}

以及 WPF 窗口的 XAML:

<Window x:Class="WpfHwndHostLayeredWindow.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:WpfHwndHostLayeredWindow"
        mc:Ignorable="d"
        Title="MainWindow" Height="450" Width="800"
        WindowStyle="None" ResizeMode="CanResizeWithGrip" AllowsTransparency="True">
    <Grid>
        <TextBlock Text="If you see this, the native control doesn't render properly"
                   HorizontalAlignment="Center"
                   VerticalAlignment="Center"/>
        <local:NativeButton Margin="16"/>
    </Grid>
</Window>

我尝试设置WS_EX_LAYERED标志,但它没有做任何事情。

有没有办法让它工作,或者它是WPF/HwndHost的(已知(限制?

分层窗口是将其内容绘制到屏幕外的窗口。这意味着系统会自动组合和重新绘制分层窗口和底层应用程序的窗口。

如果我们将本机窗口嵌入到分层窗口中,由于某些环境中的窗口类型冲突,可能无法绘制子窗口内容。

请参阅 https://learn.microsoft.com/en-us/windows/win32/winmsg/window-features#layered-windows

最新更新