karaxuna
karaxuna

Reputation: 26940

Start browser process and pass process id to close it later

My example looks similar to this:

Process.Start("http://www.webpage.com?processId=");

How to get process id before process starts? Or can I set some Guid as another identifier that will persist?

Upvotes: 0

Views: 1554

Answers (2)

Michael
Michael

Reputation: 2123

not tested

I think you should try the following:

  1. Know which browser is the default browser on the target machine. I assume firefox.
  2. Test if the browser is currently running. You can do that with var instances = Process.FindByName("firefox.exe") - you might need the full path to the local firefox installation. After that instances contains handles to all firefox instances that are currently running.

From here on we have three cases to cover:

  1. instances is an empty array. This means the browser is not running. Then you start the browser with var processHandle = Process.Start("firefox.exe"). Then you run the following command line $"firefox.exe -new-tab http://myurl.com/?id={processHandle.Id}" which (hopefully) recognizes that an instance of firefox is already running and opens the page inside the existing instance. (Executing this command can also be done with Process, but you'll have to create an Process instance without starting it, specifing the arguments in StartInfo and start it then)

  2. instances contains exactly one entry. So all we have to do is running the same command line as in case one: $"firefox.exe -new-tab http://myurl.com/?id={instances[0].Id}"

  3. instances contains multiple entries. That means that multiple firefox-windows are open. I have no solution for this. You'll have to check if the -new-tab option targets always the same window or not...

Upvotes: 1

r.anderson
r.anderson

Reputation: 161

Process p =  Process.Start("cmd.exe");
int processId = p.Id;

Upvotes: 6

Related Questions