ICompositorDesktopInterop 在 TFM .NET 5 中抛出异常

ICompositorDesktopInterop throws exception in TFM .NET 5

我试图将 C# 代码从 .NET 4.8 移植到 .NET 5,旧版本的 .NET 使用 Microsoft.Windows.SDK.Contracts,在 .NET 5 中 Microsoft.Windows.SDK.Contracts 被 [=24 取代=]Target Framework Monikers (TFMs) 我使用相同的代码尝试将合成器转换为 ICompositorDesktopInterop 但它抛出异常:

System.PlatformNotSupportedException: 'Marshalling as IInspectable is not supported in the .NET runtime.'

代码如下:

private readonly object _dispatcherQueue;
private readonly ICompositorDesktopInterop _compositorDesktopInterop;
private ICompositionTarget compositionTarget;
public Compositor compositor;

private void InitComposition(IntPtr hwnd) 
{
  ICompositorDesktopInterop interop;
  compositor = new Compositor();
  interop = compositor.As < ICompositorDesktopInterop > ();
  interop.CreateDesktopWindowTarget(hwnd, true, out compositionTarget);
  compositionTarget.Root = compositor.CreateSpriteVisual();
}

这是我使用的 Com 接口定义:

[ComImport]
[Guid("29E691FA-4567-4DCA-B319-D0F207EB6807")]
[InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
public interface ICompositorDesktopInterop 
{
  void CreateDesktopWindowTarget(IntPtr hwndTarget, bool isTopmost, out ICompositionTarget test);
}

[ComImport]
[Guid("A1BEA8BA-D726-4663-8129-6B5E7927FFA6")]
[InterfaceType(ComInterfaceType.InterfaceIsIInspectable)]
public interface ICompositionTarget 
{
  Windows.UI.Composition.Visual Root 
  {
    get;
    set;
  }
}

为什么它不能与 TFM 一起使用?我错过了什么吗?

使用 DirectN or by using InteropCompositor

可以解决 TFM 问题

对于互操作合成器:

在项目文件中设置TargetFramework

<TargetFramework>net5.0-windows10.0.19041.0</TargetFramework>

并在您的代码中使用

Compositor compositor = new Compositor();
ICompositorDesktopInterop interop = compositor.TryAs<ICompositorDesktopInterop>();
interop.CreateDesktopWindowTarget(hwnd, true, out var target).ThrowOnError();
ICompositionTarget compositionTarget = (ICompositionTarget)target;

注意:不要忘记在 MainWindow 构造函数上创建 DispatcherQueueController

所有致谢:Simon Mourier