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

如何在WebDriver关闭时立即关闭应用程序?

解决WebDriver关闭后立即关闭应用的问题

你的问题在于当前代码是被动等待异常触发——只有当WebDriver已经关闭后,你再去调用它的方法才会抛出InvalidOperationException,这时候才会执行关闭窗口的逻辑。要实现WebDriver关闭后立即关闭应用,我们需要主动监听WebDriver对应的浏览器进程状态,一旦进程退出就触发应用关闭。

下面给你两种可行的实现方式,都是基于C# WPF场景(因为你用到了App.Current.MainWindow):


方法1:精准关联WebDriver对应的浏览器进程(推荐)

这种方法通过WebDriver的窗口句柄找到对应的浏览器进程,避免误判其他浏览器窗口的关闭事件,步骤如下:

  1. 首先引入Win32 API用于获取窗口对应的进程ID:
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.Windows;

public partial class MainWindow : Window
{
    [DllImport("user32.dll")]
    private static extern uint GetWindowThreadProcessId(IntPtr hWnd, out uint lpdwProcessId);

    // 你的WebDriver实例
    private IWebDriver _driver;

    public MainWindow()
    {
        InitializeComponent();
        InitializeWebDriver();
    }

    private void InitializeWebDriver()
    {
        // 初始化你的WebDriver(这里以ChromeDriver为例)
        _driver = new ChromeDriver();

        // 获取当前WebDriver窗口的句柄并转换为IntPtr
        string windowHandle = _driver.CurrentWindowHandle;
        IntPtr windowPtr = new IntPtr(long.Parse(windowHandle));

        // 获取该窗口对应的进程ID
        GetWindowThreadProcessId(windowPtr, out uint processId);
        var browserProcess = Process.GetProcessById((int)processId);

        if (browserProcess != null)
        {
            // 启用进程退出事件监听
            browserProcess.EnableRaisingEvents = true;
            browserProcess.Exited += BrowserProcess_Exited;
        }
    }

    private void BrowserProcess_Exited(object sender, EventArgs e)
    {
        // 必须在UI线程执行窗口关闭操作
        Application.Current.Dispatcher.Invoke(() =>
        {
            App.Current.MainWindow.Close();
            // 记得释放WebDriver资源
            _driver?.Quit();
            _driver?.Dispose();
        });
    }
}

方法2:通过进程名监听(简单但可能有误判)

如果不需要精准匹配,也可以直接监听浏览器的进程名(比如Chrome是chrome.exe,Edge是msedge.exe,Firefox是firefox.exe),但注意如果用户打开了多个同类型浏览器窗口,可能会误触发:

private void InitializeWebDriver()
{
    _driver = new ChromeDriver();

    // 获取第一个非后台的Chrome进程(仅作示例,不精准)
    var browserProcess = Process.GetProcessesByName("chrome")
                                .FirstOrDefault(p => p.MainWindowHandle != IntPtr.Zero);

    if (browserProcess != null)
    {
        browserProcess.EnableRaisingEvents = true;
        browserProcess.Exited += (s, e) =>
        {
            Application.Current.Dispatcher.Invoke(() =>
            {
                App.Current.MainWindow.Close();
                _driver?.Quit();
                _driver?.Dispose();
            });
        };
    }
}

关键说明:

  • 为什么要在Dispatcher.Invoke里执行关闭?因为进程退出事件是在非UI线程触发的,WPF窗口操作必须在UI线程执行,否则会报错。
  • 记得在关闭应用前释放WebDriver资源(Quit()和Dispose()),避免残留进程。
  • 不同浏览器的进程名需要对应修改,比如Edge是msedge.exe,Firefox是firefox.exe。

这样修改后,只要用户关闭了WebDriver对应的浏览器窗口,应用就会立即触发关闭逻辑,不用等到后续操作抛出异常了。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.29 08:16:21