加入收藏 | 设为首页 | 会员中心 | 我要投稿 大连站长网 (https://www.0411zz.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 服务器 > 系统 > 正文

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

发布时间:2021-05-12 10:26:19 所属栏目:系统 来源:网络整理
导读:我有一个在我的PoSh会话后台运行的FileSystemWatcher实例,用于监视文本文件的更改. PoSh事件订阅者附加到此事件,并在触发时通过调用Start-Process启动控制台程序.该程序从当前前景窗口(我的PoSh控制台)窃取焦点.从PoSh事件订阅者调用SetForegroundWindow将

我有一个在我的PoSh会话后台运行的FileSystemWatcher实例,用于监视文本文件的更改. PoSh事件订阅者附加到此事件,并在触发时通过调用Start-Process启动控制台程序.该程序从当前前景窗口(我的PoSh控制台)窃取焦点.从PoSh事件订阅者调用SetForegroundWindow将焦点返回到我的PoSh控制台不起作用. SwitchToThisWindow大部分时间都可以工作,但根据MSDN文档,它不能被使用.

我是否可以阻止Start-Process在这种情况下窃取焦点,或者在事件触发之前将其从事件订阅者设置回到具有该事件的窗口?

解决方法

对我来说,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或使用例如PowerShell控制台(http://sourceforge.net/projects/console/)然后MainWindowHandle是您的主机程序的句柄.
因此,不需要(Get-Process -id $pid).MainWindowHandle,你需要[技巧] :: 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类的文档中获取和更改的示例

(编辑:大连站长网)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!