gpt4 book ai didi

winapi - 如何从 Powershell 事件订阅者操作​​设置前景窗口

转载 作者:行者123 更新时间:2023-12-01 07:22:20 27 4
gpt4 key购买 nike

我有一个 文件系统观察者 在我的 PoSh session 后台运行的实例,监视文本文件的更改。 PoSh 事件订阅者附加到此事件,并在触发时通过调用 启动控制台程序。启动流程 .该程序从当前的前景窗口(我的 PoSh 控制台)中窃取焦点。调用 设置前景窗口 从 PoSh 事件订阅者返回焦点到我的 PoSh 控制台不起作用。 切换到此窗口 大多数情况下确实有效,但根据 MSDN 文档,不应使用它。

我可以预防吗启动流程在这种情况下窃取焦点或将其从事件订阅者设置回触发此事件之前拥有它的窗口?

最佳答案

给我 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 或使用例如Console ( 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)

从关于 Process 的 msdn 文档中获取和更改的示例类(class)

关于winapi - 如何从 Powershell 事件订阅者操作​​设置前景窗口,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2556872/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com