Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to open "Microsoft Edge" from c# and wait for it to be closed?

I'm building a Windows Form application and I want to open "Microsoft Edge" through my app with a specific URL and wait until the user closes the Edge Window.

I tried it with this code:

using (Process p = Process.Start("microsoft-edge:www.mysite.com"))
{
    p.WaitForExit();
}

When I execute this code, Edge is launching with the correct URL ... but got a null object reference. The "p" object that I'm getting from Process.Start is null.

I think it's related to the reuse of Windows application.

Does anyone have a workaround/have an idea how I can wait for the user to close Edge?

like image 378
Aviram Fireberger Avatar asked Mar 14 '23 06:03

Aviram Fireberger


1 Answers

Finally I did managed to do so: When you launch Edge (at least) two process get created: MicrosoftEdge and MicrosoftEdgeCP.

MicrosoftEdgeCP - foreach tab. So we can "wait" on this new tab process that was just created.

//Edge process is "recycled", therefore no new process is returned.
Process.Start("microsoft-edge:www.mysite.com");

//We need to find the most recent MicrosoftEdgeCP process that is active
Process[] edgeProcessList = Process.GetProcessesByName("MicrosoftEdgeCP");
Process newestEdgeProcess = null;

foreach (Process theprocess in edgeProcessList)
{
    if (newestEdgeProcess == null || theprocess.StartTime > newestEdgeProcess.StartTime)
    {
        newestEdgeProcess = theprocess;
    }
}

newestEdgeProcess.WaitForExit();
like image 110
Aviram Fireberger Avatar answered Mar 17 '23 07:03

Aviram Fireberger