我有一个 winui 3 项目,我尝试使用 win api 调用
但问题是,如果我提前调用
DwmRegisterThumbnail
,它就会失败。
所以我尝试在第一个
Activated
事件上调用它,但失败了。
我也尝试过VisibilityChanged
但同样的问题。
public sealed partial class MainWindow : Window
{
private bool hasBeenActivated = false;
private nint thumbnailId;
public MainWindow()
{
this.InitializeComponent();
this.Activated += MainWindow_Activated;
this.Closed += MainWindow_Closed;
}
private void MainWindow_Activated(object sender, WindowActivatedEventArgs args)
{
if (!hasBeenActivated)
{
hasBeenActivated = true;
SetupDisplay();
}
}
private void SetupDisplay()
{
try
{
var otherWindowHandle = //Get handle to different window!
var handle = WinRT.Interop.WindowNative.GetWindowHandle(this);
PInvoke.DwmRegisterThumbnail((Windows.Win32.Foundation.HWND)handle, otherWindowHandle, out thumbnailId).ThrowOnFailure();
PInvoke.DwmUpdateThumbnailProperties(thumbnailId, new Windows.Win32.Graphics.Dwm.DWM_THUMBNAIL_PROPERTIES
{
dwFlags = (uint)DWM_FLAGS.DWM_TNP_VISIBLE | (uint)DWM_FLAGS.DWM_TNP_RECTDESTINATION,
fVisible = true,
rcDestination = new Windows.Win32.Foundation.RECT
{
left = 0,
top = 0,
right = this.AppWindow.Size.Width,
bottom = this.AppWindow.Size.Height
}
});
}
catch (Exception ex) {
Debug.WriteLine("Failed to setup display, trying again, " + ex.ToString());
}
}
private void MainWindow_Closed(object sender, WindowEventArgs args)
{
PInvoke.DwmUnregisterThumbnail(thumbnailId).ThrowOnFailure();
}
}
对
DwmRegisterThumbnail
的调用失败,并显示 HResult -2147024809
,并显示消息 Value does not fall within the expected range.
。
-2147024809
是什么意思,我是否可以使用其他一些事件来触发链中稍后不会发生此问题的事件?
经过一番谷歌搜索后我发现:
The handle to the window that will use the DWM thumbnail. Setting the destination window handles to anything other than a top level window type will result in an E_INVALIDARG.
问题是如何检测我的窗口何时是顶级窗口。
Window
没有加载事件。您可以做的是使用其 Loaded
的 Content
事件。
MainWindow.xaml
<Window
x:Class="WinUI3Example.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:local="using:WinUI3Example"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d">
<local:MainPage Loaded="MainPage_Loaded" />
</Window>
MainWindow.xaml.cs
using Microsoft.UI.Xaml;
namespace WinUI3Example;
public sealed partial class MainWindow : Window
{
public MainWindow()
{
this.InitializeComponent();
}
private void MainPage_Loaded(object sender, RoutedEventArgs e)
{
// Your logic here:
}
}