Avalonia本身没有提供直接使用Native句柄承载窗口的方法,但可以通过使用IWIndowImpl实现自定义的窗口承载方式。
下面是一个示例代码,可以实现使用Native句柄承载Avalonia窗口:
using Avalonia;
using Avalonia.Controls;
using Avalonia.Controls.Platform;
using Avalonia.Platform;
using Avalonia.Rendering;
using Avalonia.Threading;
using System;
namespace NativeWindowImpl
{
class Program
{
static void Main(string[] args)
{
// 初始化Avalonia
AppBuilder.Configure()
.UsePlatformDetect()
.SetupWithoutStarting();
// 创建Native窗口
var nativeWindow = CreateNativeWindow();
// 创建Avalonia窗口
Window window = new Window();
window.Title = "Avalonia Window with Native Handle";
window.Width = 640;
window.Height = 480;
// 获取窗口句柄
IntPtr hWnd = nativeWindow.Handle;
// 使用IWIndowImpl承载窗口
var windowImpl = AvaloniaLocator.Current.GetService();
windowImpl.Attach(window);
// 将Avalonia窗口与Native窗口绑定
windowImpl.Resize(new PixelSize((int)window.Width, (int)window.Height));
windowImpl.SetOwner(hWnd);
windowImpl.Show();
// 保证Avalonia资源已经准备好
Dispatcher.UIThread.InvokeAsync(() =>
{
// 关闭Native窗口
nativeWindow.Close();
});
// 运行Avalonia应用程序
AppBuilder.Configure()
.UsePlatformDetect()
.SetupWithoutStarting()
.StartWithClassicDesktopLifetime(args);
}
private static INativeWindow CreateNativeWindow()
{
// 创建一个Win32窗口
var factory = AvaloniaLocator.Current.GetService();
var hwndSource = factory.CreateHwnd(new HwndCreationParameters
{
ExtendClientAreaToDecorationsHint = true,
ParentHandle = IntPtr.Zero
上一篇:AvaloniaLocator Current在Linux中不存在。
下一篇:AvaloniaOpenFolderDialog在ReactiveCommand中使用时引发“来自无效线程的调用”错误。