Launch URL from C# and detect when browser is closed

40 Views Asked by At

Is there a way to open a webbrowser and detect when the browser is closed through C#?

The basic approach is to use Process.Start and add an event listener to Exited; this works for other programs like Notepad.exe, or for google chrome if it isn't already running. But if Chrome is already running the launched process immediately exits and the URL is opened in the existing chrome. This happens even with the --new-window command line argument - it opens in a new window, but not in a new process.

Some googling suggests that the only way to open Chrome in a new process is to specify --user-data-dir. This "works" but the first time it's run it asks me to log in in a separate window, and since it's using a different profile, any existing bookmarks/settings will be lost. This is also going to be used in a locked-down environment, so I can't guarantee this will work, and I have no easy way to test this on the real hardware.

I don't truly need this to run in a separate process, so long as the C# program can detect when the new window is closed. Running as a separate process would just be one way to do it, but it sounds like that's not an option.

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");  //Opens chrome and immediately exits if it's already running.
    //var proc = OpenProc("chrome.exe", $"www.google.com --user-data-dir={folder} --bwsi"); //Works, but causes other problems.
    //var proc = OpenProc("chrome.exe", $"www.google.com --profile-directory=\"Profile 1\"");   //Immediately exits.
    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();
    proc.EnableRaisingEvents = true;
    return proc;
}
0

There are 0 best solutions below