powershell - Start-Process -wait + always on top (topmost)

578 views Asked by At

i have the following code:

Start-Process -FilePath myprogram.exe -Wait
# ... some other code to be executed AFTER the previous process has ended

What i need

I need to start the process with -wait as you can see, but i also need that that the window of that process to be always on top (or "topmost").

What i tried

I've seen this question/answer: https://stackoverflow.com/a/73319269

And i've tried what the solution suggests, like this:

$User32 = Add-Type -Debug:$False -MemberDefinition '
    [DllImport("user32.dll")] public static extern bool SetWindowPos(IntPtr hWnd, IntPtr hWndInsertAfter, int X,int Y, int cx, int cy, uint uFlags);
' -Name "User32Functions" -namespace User32Functions -PassThru

$proc = Start-Process -FilePath myprogram.exe -Passthru

$Handle = ($proc).MainWindowHandle
[Void]$User32::SetWindowPos($Handle, -1, 0, 0, 0, 0, 0x53)

But

  • it doesn't work, the myprogram.exe window is not topmost
  • i had to remove -wait to add and utilise -passthru, so how can i detect when the execution of myprogram.exe is over?

Thank you for your help.

1

There are 1 answers

2
iRon On

Taking cmd.exe for a Minimal, Reproducible Example:

$User32 = Add-Type -Debug:$False -MemberDefinition '
    [DllImport("user32.dll")] public static extern bool SetWindowPos(IntPtr hWnd, IntPtr hWndInsertAfter, int X,int Y, int cx, int cy, uint uFlags);
' -Name "User32Functions" -namespace User32Functions -PassThru

Start-Process -FilePath cmd.exe
Start-Sleep 1 # wait for the process to initialize
$Proc = Get-Process cmd
$Handle = ($Proc).MainWindowHandle
[Void]$User32::SetWindowPos($Handle, -1, 0, 0, 0, 0, 0x53)
Wait-Process $Proc.id