I have a FileSystemWatcher instance running in the background of my PoSh session watching for changes to text files. A PoSh event subscriber is attached to this event and, when fired, it launches a console program by calling Start-Process. This program steals de focus from the current foreground window (my PoSh console). Calling SetForegroundWindow from the PoSh event subscriber to return the focus to my PoSh console doesn't work. SwitchToThisWindow does work most of the time, but according to the MSDN docs, it shoulnd't be used.
Can I prevent Start-Process from stealing the focus in this situation or set it back from the event subscriber to the window that had it before this event is fired?
For me
SetForegroundWindowworks well. Check this code:But note that if you host PowerShell or use e.g. Console (http://sourceforge.net/projects/console/) then MainWindowHandle is the handle of your host program. So instead of
(Get-Process -id $pid).MainWindowHandleyou would need[tricks]::SetForegroundWindow((Get-Process console).MainWindowHandle).Example with timer event:
Otherwise if you run process that has its window hidden, it could solve your problem.
Example taken and altered from documentation on msdn about Process class