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

如何通过C#启动浏览器URL并检测浏览器窗口关闭状态?

如何用C#打开浏览器并检测其关闭状态?

常规实现思路是使用Process.Start启动浏览器进程,并监听Exited事件。这种方案对Notepad.exe或者未运行的Google Chrome有效,但当Chrome已经处于运行状态时,启动的进程会立即退出,目标URL会在已有的Chrome窗口中打开——哪怕加上--new-window命令行参数,也只会打开新窗口而非新进程,导致无法通过进程退出事件检测窗口关闭。

搜索后得知,唯一能让Chrome以全新进程启动的方式是指定--user-data-dir参数。这个方案确实能触发进程的Exited事件,但存在明显弊端:首次运行时会要求在单独窗口登录,且因为使用独立配置文件,现有书签、浏览器设置都无法复用。此外,该方案在锁定环境中的有效性无法保证,也难以在实际硬件环境中测试。

实际上我们的核心需求并非一定要启动单独进程,只要C#程序能检测到新打开的浏览器窗口关闭即可——单独进程只是实现手段之一,但目前这条路径显然不可行。

以下是测试用的代码示例:

using System;
using System.Diagnostics;
using System.IO;
using System.Threading;

class Program
{
    static void Main(string[] args)
    {
        var folder = Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location);
        folder = Path.Combine(folder!, "Chrome");

        var proc = OpenProc("chrome.exe", $"www.google.com --new-window");  // Chrome已运行时,进程会立即退出
        //var proc = OpenProc("chrome.exe", $"www.google.com --user-data-dir={folder} --bwsi"); // 有效但附带其他问题
        //var proc = OpenProc("chrome.exe", $"www.google.com --profile-directory=\"Profile 1\"");   // 进程仍会立即退出
        proc!.Exited += Proc_Exited;
        Thread.Sleep(10000);
    }

    private static void Proc_Exited(object? sender, EventArgs e)
    {
        Console.WriteLine("Proc exited called.");
    }

    public static Process OpenProc(string browserExe, string args)
    {
        Console.WriteLine($"Open url using {browserExe}, args:  {args}");
        var ps = new ProcessStartInfo(browserExe, args)
        {
            UseShellExecute = true,
            Verb = "open"
        };

        var proc = Process.Start(ps) ?? throw new Exception("Failed to start process");
        proc.EnableRaisingEvents = true;
        return proc;
    }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.27 02:51:12