调用 CompositionCapabilities.GetForCurrentView 时获取访问被拒绝异常

Getting Access is denied exception when calling CompositionCapabilities.GetForCurrentView

我在调用 CompositionCapabilities.GetForCurrentView 时遇到以下异常。

System.UnauthorizedAccessException: 'Access is denied. (Exception from HRESULT: 0x80070005 (E_ACCESSDENIED))'

public App()
{
    this.InitializeComponent();
    this.Suspending += OnSuspending;

    // Exception happens here.
    var capabilities = CompositionCapabilities.GetForCurrentView();
}

奇怪的是代码编译正常所以我假设 API 可用。我是否需要在 Package.appxmanifest 中声明任何功能?

您不需要申报任何东西。方法调用太早了

所以不要在构造函数中调用它,而是在 Window 创建后立即调用它 -

protected override void OnWindowCreated(WindowCreatedEventArgs args)
{
    if (ApiInformation.IsApiContractPresent("Windows.Foundation.UniversalApiContract", 4))
    {
        var capabilities = CompositionCapabilities.GetForCurrentView();
        var areEffectsSupported = capabilities.AreEffectsSupported();
        var areEffectsFast = capabilities.AreEffectsFast();
    }

    base.OnWindowCreated(args);
}

请注意,您需要添加一个检查以查看 API 是否也受支持,就像上面的代码一样。