I have an application which lets the user open a customers profile in a web-based CRM and I need to make sure that the user cannot have two profiles open this way. I only need to do this for Firefox. I've managed to do this by simply running Firefox as a new System.Diagnostics.Process, keeping it in memory and closing when a new customer is being pulled up.
The problem is that it only works if I don't have another Firefox window opened at the same time. Since I can't disclose the CRM or customers I will be using Google and Bing instead.
If I have a window opened this happens:
- Open a Firefox window normally (via Windows).
- Run the app and have it open Google in a new Firefox window - works OK.
- Have the app open Bing - the browser process has now somehow ended (even though the browser window is still up) and I cannot close it - it will crash with a "Process has exited, so the requested information is not available." exception if I try to Close(). Process.HasExited also shows true.
If I open a new Firefox window normally after opening Google from the app, but before Bing it will close the new window instead.
I have managed to get around this using Selenium, but that feels like a very large stick to use on a small functionality (the Selenium DLL and driver weights more than the entire app).
I would be very grateful for any advice on how to make this work, or some alternative ways of achieving the same effect.
Here's my code:
class MyClass
{
public static Process StartBrowser(Process proc, string url)
{
string AppPath = Environment.ExpandEnvironmentVariables(@"C:Program FilesMozilla Firefoxfirefox.exe");
if (!File.Exists(AppPath))
throw new ArgumentException(string.Format("some other exception message");
if (proc != null && proc.HasExited)
{
Console.WriteLine("Process has exited");
}
else if (proc != null && !proc.HasExited)
{
proc.CloseMainWindow();
proc.Close();
}
proc = new Process();
proc.StartInfo = new ProcessStartInfo(AppPath, string.Format($"-foreground -new-window {url}"));
proc.Start();
return proc;
}
}
Here's how I call the above class in a test application:
public static void FirefoxTest()
{
System.Diagnostics.Process proc = null;
Console.WriteLine("Window 1");
proc = MyClass.StartBrowser(proc, "http://www.google.com");
Console.WriteLine("Press Enter for the second window...");
Console.ReadLine();
Console.WriteLine("Window 2");
MyClass.StartBrowser(proc, "http://www.bing.com");
}
question from:
https://stackoverflow.com/questions/65906289/how-to-open-and-close-a-firefox-window-in-c-sharp-with-a-different-instance-of-f 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…