对我来说SetForegroundWindow
效果很好。检查此代码:
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)
但请注意,如果您托管 PowerShell 或使用例如控制台 ( http://sourceforge.net/projects/console/ ),则 MainWindowHandle 是您的主机程序的句柄。因此,(Get-Process -id $pid).MainWindowHandle
您将需要[tricks]::SetForegroundWindow((Get-Process console).MainWindowHandle)
.
计时器事件示例:
$timer = New-Object Timers.Timer
$timer.Interval = 5000
$h = (Get-Process -id $pid).MainWindowHandle
$action = {
notepad;
sleep -sec 1; # wait until the program starts (very simple approach)
[Tricks]::SetForegroundWindow($h) }
Register-ObjectEvent $timer Elapsed -Action $action
$timer.Start()
否则,如果您运行隐藏其窗口的进程,它可以解决您的问题。
$ps = new-object system.diagnostics.processstartinfo 'notepad'
$ps.windowStyle = 'hidden'
[system.diagnostics.process]::Start($ps)
从 msdn 上有关Process类的文档中获取和更改的示例