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

WinUI3中如何更改已创建的CoreWebView2的父窗口?

解决WinUI3中Tab拖出后WebView2 ParentWindow未更新的问题

问题原因

当你把包含WebView2的Tab拖到新窗口时,WebView2底层的CoreWebView2Controller仍绑定着原窗口的句柄(HWND),这就导致点击WebView2会唤起旧窗口,关闭旧窗口时CoreWebView2Controller被销毁,WebView2也就随之消失。

解决方案

你可以通过WebView2.CoreWebView2.Controller获取到CoreWebView2Controller实例,直接将其ParentWindow属性更新为新窗口的句柄即可,无需重新初始化WebView2。

修改后的代码

using WinRT.Interop;

private async void Tabcontrol_TabDroppedOutside(TabView sender, TabViewTabDroppedOutsideEventArgs args)
{
    sender.TabItems.Remove(args.Tab);
    var newWindow = App.AddNewWindow();

    // 从Tab中获取WebView2控件(根据你的实际布局调整获取逻辑)
    if (args.Tab.Content is WebView2 webView)
    {
        // 确保CoreWebView2已完成初始化
        if (webView.CoreWebView2 == null)
        {
            await webView.EnsureCoreWebView2Async();
        }

        // 获取新窗口的HWND
        IntPtr newWindowHandle = WindowNative.GetWindowHandle(newWindow);
        // 更新CoreWebView2Controller的父窗口句柄
        webView.CoreWebView2.Controller.ParentWindow = newWindowHandle;
    }

    newWindow.Tabcontrol.TabItems.Add(args.Tab);
}

关键说明

  1. 窗口句柄获取:用WindowNative.GetWindowHandle方法可以拿到WinUI3窗口的HWND,这是WinUI3和原生Windows API交互的常规方式。
  2. CoreWebView2Controller访问:WebView2.CoreWebView2包含Controller属性,通过它能直接操作底层控制器,包括修改ParentWindow。
  3. 初始化检查:如果WebView2还没完成初始化(CoreWebView2为null),要先调用EnsureCoreWebView2Async完成初始化后再修改父窗口句柄。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.19 16:24:52