简体   繁体   中英

How can I wait until `start-process notepad` has finished creating its window?

When I use start-process to create a new process and assign it to a variable...

 $np = start-process -passThru notepad

... and then query .MainWindowHandle ...

 $np.MainWindowHandle

... I seem to be given the HWND of the notepad.

However, when I try to do the same thing in one go...

(start-process -passThru notepad).MainWindowHandle

... I am given 0 .

This is probably the case because MainWindowHandle is evaluated before notepad has created its window.

So, is there a way, without using start-sleep or going into a loop that repeadetly queries the value of MainWindowHandle , to wait until notepad is done starting up?

So, is there a way,

Yes

without using start-sleep or going into a loop that repeadetly queries the value of MainWindowHandle

Not that I can think of:)

# Define a timeout threshold 10 seconds into the future
$threshold = (Get-Date).AddSeconds(10)

# Start the process
$proc = Start-Process notepad -PassThru

while(-not $proc.HasExited -and ((Get-Date) -lt $threshold -or $proc.MainWindowTitle -eq 0)){
  Start-Sleep -MilliSeconds 250
}
if($proc.MainWindowTitle -eq 0){
  if(-not $proc.HasExited)
    $proc.Terminate()
  }
  throw 'Failed to spawn window in time'
  return
}

# Do stuff with $proc.MainWindowHandle

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM