简体   繁体   English

ICompositorDesktopInterop 在 TFM 中抛出异常 .NET 5

[英]ICompositorDesktopInterop throws exception in TFM .NET 5

I was trying to port a C# code from .NET 4.8 to .NET 5, older version of .NET was using Microsoft.Windows.SDK.Contracts , In .NET 5 Microsoft.Windows.SDK.Contracts is replaced by Target Framework Monikers (TFMs) I used the same code an tried to cast the compositor to ICompositorDesktopInterop but it throws exception: I was trying to port a C# code from .NET 4.8 to .NET 5, older version of .NET was using Microsoft.Windows.SDK.Contracts , In .NET 5 Microsoft.Windows.SDK.Contracts is replaced by Target Framework Monikers (TFMs) I used the same code an试图将合成器转换为 ICompositorDesktopInterop 但它抛出异常:

System.PlatformNotSupportedException: 'Marshalling as IInspectable is not supported in the .NET runtime.' System.PlatformNotSupportedException:“.NET 运行时不支持编组为 IInspectable。”

Here is the code:这是代码:

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();
}

This is the Com Interface definition that i have used:这是我使用的 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;
  }
}

Why is it not working with TFM?为什么它不能与 TFM 一起使用? Is there something I missed?我错过了什么吗?

The issue with TFM can be solved by using DirectN or by using InteropCompositor TFM 的问题可以通过使用DirectN或使用InteropCompositor来解决

For InteropCompositor:对于互操作合成器:

Set the TargetFramework in the project file在项目文件中设置 TargetFramework

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

and in your code use并在您的代码中使用

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

Note: Don't forget to create DispatcherQueueController on MainWindow Constructor.注意:不要忘记在 MainWindow Constructor 上创建DispatcherQueueController

All Credits to: Simon Mourier所有致谢: Simon Mourier

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM