You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Win32中WinUI3的DesktopWindowXamlSource转IDesktopWindowXamlSourceNative失败(E_NOINTERFACE)

解决WinUI3 XAML Islands中DesktopWindowXamlSource转换为互操作接口失败的问题

核心问题原因

你误用了UWP XAML Islands的互操作接口IDesktopWindowXamlSourceNative,而WinUI3的DesktopWindowXamlSource对应的是专属的IDesktopWindowXamlSourceNative2接口,同时缺少必要的头文件和库链接配置。

具体修复步骤

  1. 替换头文件
    将代码中的<windows.ui.xaml.hosting.desktopwindowxamlsource.h>替换为WinUI3专属的互操作头文件:

    #include <microsoft.ui.xaml.hosting.desktopwindowxamlsource.h>
    
  2. 添加库链接
    在代码中添加WinUI3库的链接指令,或者在项目属性的「链接器->输入->附加依赖项」中添加Microsoft.ui.xaml.lib:

    #pragma comment(lib, "Microsoft.ui.xaml.lib")
    
  3. 替换互操作接口类型
    将接口转换代码中的IDesktopWindowXamlSourceNative改为IDesktopWindowXamlSourceNative2:

    auto interop = desktopWindowXamlSource.as<IDesktopWindowXamlSourceNative2>();
    
  4. 验证Windows SDK版本
    确保项目的Windows SDK版本设置为**10.0.19041.0(Windows 10 2004)**或更高版本,WinUI3对最低SDK版本有要求。

修复后的完整代码示例

#include "framework.h"
#include "WinUI3XamlIslandsWin32.h"

#include <winrt/Microsoft.UI.Dispatching.h>
#include <winrt/Microsoft.UI.Xaml.Hosting.h>
#include <microsoft.ui.xaml.hosting.desktopwindowxamlsource.h>
#include <cassert>

#pragma comment(lib, "Microsoft.ui.xaml.lib")

int APIENTRY wWinMain(_In_ HINSTANCE hInstance,
                     _In_opt_ HINSTANCE hPrevInstance,
                     _In_ LPWSTR    lpCmdLine,
                     _In_ int       nCmdShow)
{
    winrt::init_apartment(winrt::apartment_type::single_threaded);
    auto dispatcherQueueController = winrt::Microsoft::UI::Dispatching::DispatcherQueueController::CreateOnCurrentThread();
    auto windowsXamlManager = winrt::Microsoft::UI::Xaml::Hosting::WindowsXamlManager::InitializeForCurrentThread();
    
    winrt::Microsoft::UI::Xaml::Hosting::DesktopWindowXamlSource desktopWindowXamlSource;
    auto interop = desktopWindowXamlSource.as<IDesktopWindowXamlSourceNative2>();
    assert(interop != nullptr);

    // 后续可以调用interop->AttachToWindow(hWnd)将XAML源附加到Win32窗口
    return EXIT_SUCCESS;
}

内容的提问来源于stack exchange,提问作者Litherum

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.05 14:15:20