It SetForegroundWindowworks well for me . Check this code:
Add-Type @"
using System;
using System.Runtime.InteropServices;
public class Tricks {
[DllImport("user32.dll")]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool SetForegroundWindow(IntPtr hWnd);
}
"@
sleep -sec 2
$h = (Get-Process firefox).MainWindowHandle
[void] [Tricks]::SetForegroundWindow($h)
sleep -sec 2
$h = (Get-Process -id $pid).MainWindowHandle
[void] [Tricks]::SetForegroundWindow($h)
But remember that if you host PowerShell or use, for example, the Console ( http://sourceforge.net/projects/console/ ), then MainWindowHandle is the handle to your host program. Therefore, (Get-Process -id $pid).MainWindowHandleyou will need instead [tricks]::SetForegroundWindow((Get-Process console).MainWindowHandle).
Example with a timer event:
$timer = New-Object Timers.Timer
$timer.Interval = 5000
$h = (Get-Process -id $pid).MainWindowHandle
$action = {
notepad;
sleep -sec 1;
[Tricks]::SetForegroundWindow($h) }
Register-ObjectEvent $timer Elapsed -Action $action
$timer.Start()
Otherwise, if you run a process that hides its window, it may solve your problem.
$ps = new-object system.diagnostics.processstartinfo 'notepad'
$ps.windowStyle = 'hidden'
[system.diagnostics.process]::Start($ps)
, msdn Process class