Search code examples
c#winformsprocessfocus

How to Set Focus Back To Calling Form After Starting A Process (Chrome)


I open up a Chrome browser window from my program using Process.Start() but the new opened chrome browser tab(s) covers the screen. But I want my application to maintain its focus after creating these chrome browser tab(s).

I will have one brower window open but several chrome tabs showing different URLs.

Here is what I've tried which is similar to the answer at How to set focus back to form after opening up a process (Notepad)?. But doesn't work for me.

[DllImport("user32.dll")]
[return: MarshalAs(UnmanagedType.Bool)]
static extern bool SetForegroundWindow(IntPtr hWnd)

// this code will get called several times with a different URL in Arguments property

Process p = new Process();
p.StartInfo = new ProcessStartInfo("Chrome.exe");
p.StartInfo.CreateNoWindow = true;

p.StartInfo.Arguments = "https:/google.com";
p.Start();

p.WaitForInputIdle();
SetForegroundWindow(this.Handle);

Solution

  • Just adding a short delay seemed to work fine for me:

    private void button1_Click(object sender, EventArgs e)
    {
        OpenUrl("https:/google.com");
    }
    
    private async void OpenUrl(string url)
    {
        Process p = new Process();
        p.StartInfo = new ProcessStartInfo("Chrome.exe");
        p.StartInfo.CreateNoWindow = true;
        p.StartInfo.Arguments = url;
        p.Start();
        p.WaitForInputIdle();
        await Task.Delay(50);
        SetForegroundWindow(this.Handle);
    }