Process.Start() does not bring the window to the foreground

Nevin Sunny 0 Reputation points
2023-07-21T05:31:54.8466667+00:00
Hi, we have code in place to launch an application via bundles. But we see that on launching the bundle, it randomly comes into focus or remains in the background (not minimized).



     proc = Process.Start(SetupProcessStartInfo(launchData));
We have tried using some native APIs like SetForegroundWindow() and 

handle = procRun.MainWindowHandle;
        SwitchToThisWindow(handle, true);
But these don't seem to do the trick.



Any help around this would be appreciated.


Windows for business | Windows Server | User experience | PowerShell
Developer technologies | C#
0 comments No comments
{count} votes

3 answers

Sort by: Most helpful
  1. Olaf Helper 47,441 Reputation points
    2023-07-21T06:56:26.4833333+00:00

  2. Rich Matheisen 47,901 Reputation points
    2023-07-21T18:38:13.3133333+00:00

    You can use the Start-Process cmdlet with the -WindowStyle parameter. The acceptable states are:

    • Normal
    • Hidden
    • Minimized
    • Maximized

  3. Rich Matheisen 47,901 Reputation points
    2023-07-23T21:29:02.6833333+00:00

    It may not be as easy as you think.

    If you use Start-Process with the -PassThru parameter and assign the result to a variable you may be able to use the MailWindowHandle property, but only if the window is visible (e.g., not minimized, and not behind another window), and that's not something you can rely on.

    To get the necessary information will probably require you to use P/Invoke and the Windows API: (https://stackoverflow.com/questions/21239260/get-main-window-of-a-process-if-not-visible-net-powershell)

    You may be able to find a working example in PowerShell given the information in that link (and there are probably other posts, too).

    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.