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

Windows Forms应用中WebView2的DownloadStarting事件未触发问题

WebView2 DownloadStarting事件未触发的解决办法

核心问题:事件绑定与处理方法名不匹配

你在WebView_CoreWebView2InitializationCompleted方法中绑定的事件处理方法是CoreWebView2_DownloadStarting,但实际定义的处理方法名为CoreWebView2_DownloadStarting1(多了后缀1),导致事件无法关联到正确的逻辑,自然不会触发。

修正方案

你可以选择以下两种方式之一修正:

方式1:调整事件绑定的方法名,匹配实际定义的方法

private async void InitBrowser()
{
    var environment = await CoreWebView2Environment.CreateAsync(null, @"C:\Temp", null);
    webView.CoreWebView2InitializationCompleted += WebView_CoreWebView2InitializationCompleted;
    await webView.EnsureCoreWebView2Async(environment);
    webView.NavigationCompleted += WebView_NavigationCompleted;
    webView.Source = new Uri("myurl");
    
}
private void WebView_CoreWebView2InitializationCompleted(object sender, CoreWebView2InitializationCompletedEventArgs e)
{
    // 修正绑定的方法名,与实际处理方法一致
    webView.CoreWebView2.DownloadStarting += CoreWebView2_DownloadStarting1;
    
}
private void CoreWebView2_DownloadStarting1(object sender, CoreWebView2DownloadStartingEventArgs e)
{
    downloadOperation = e.DownloadOperation;
    e.Handled = true;
    e.ResultFilePath = Savefile();
}

方式2:调整处理方法的名称,匹配事件绑定的名称

private void WebView_CoreWebView2InitializationCompleted(object sender, CoreWebView2InitializationCompletedEventArgs e)
{
    webView.CoreWebView2.DownloadStarting += CoreWebView2_DownloadStarting;
    
}
// 将方法名改为与绑定一致的CoreWebView2_DownloadStarting
private void CoreWebView2_DownloadStarting(object sender, CoreWebView2DownloadStartingEventArgs e)
{
    downloadOperation = e.DownloadOperation;
    e.Handled = true;
    e.ResultFilePath = Savefile();
}

额外检查点

  1. 确保Savefile()方法返回的是包含文件名和扩展名的有效路径,否则可能导致下载逻辑异常
  2. 可在初始化完成事件中检查WebView2是否初始化成功,排查潜在的初始化问题:
private void WebView_CoreWebView2InitializationCompleted(object sender, CoreWebView2InitializationCompletedEventArgs e)
{
    if (e.IsSuccess)
    {
        webView.CoreWebView2.DownloadStarting += CoreWebView2_DownloadStarting1;
    }
    else
    {
        MessageBox.Show($"WebView2初始化失败: {e.InitializationException.Message}");
    }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.02 05:20:24