【发布时间】:2018-03-03 06:37:01
【问题描述】:
我知道这可以通过使用 alt-tab 轻松完成,但创建此脚本的主要目的是自学一些 PowerShell 基础知识。
我正在编写一个脚本,该脚本在运行时会在 powershell 和当前前台窗口之间切换前台窗口。我阅读了this question 并使用其中一个答案来获取检索当前前景窗口的代码,但它似乎没有抓取正确的窗口 - 它似乎抓取了 explorer.exe
下面是我的脚本代码,希望对 cmets 有帮助:
# Toggle-PowerShell.ps1
# Toggles focus between powershell and the current active window.
# If this script isn't run with -NoProfile, it will switch focus to itself.
. $PSScriptRoot\..\Functions\Toggle-Window.ps1
Add-Type @"
using System;
using System.Runtime.InteropServices;
public class Util {
[DllImport("user32.dll")]
public static extern IntPtr GetForegroundWindow();
}
"@
$a = [util]::GetForegroundWindow()
# Get-Unique may be unnecessary here, but including it for the case when
# working with Chrome as the stored process
$storedProcess=get-process | ? { $_.mainwindowhandle -eq $a } | Get-Unique
If(Test-Path $PSScriptRoot\Toggle-PowerShell.temp)
{
$tempArray=(Get-Content $PSScriptRoot\Toggle-Powershell.temp)
# the id number is at index three of tempArray
Show-Process -Process (Get-Process -id $tempArray[3])
# delete the file so the next time we run the script it toggles to PS
Remove-Item $PSScriptRoot\Toggle-PowerShell.temp
} Else
{
$propertiesFile=$PSScriptRoot\..\currentSession.properties
$propertiesMap = convertfrom-stringdata (get-content $propertiesfile -raw)
Show-Process -Process (Get-Process -id $propertiesMap.'PowerShellPID')
# write a new temp file that contains the stored process's id
# so that the next time this script is run it toggles back
$storedProcess | Select-Object Id > $PSScriptRoot\Toggle-PowerShell.temp
}
我在想也许我应该尝试获取活动窗口而不是前景窗口,但another question's answer 说前景意味着活动。
我使用的是 Windows 10。
编辑:我认为它可能使用 explorer.exe 作为“前景窗口”,因为我通过从资源管理器启动的快捷方式调用脚本。
【问题讨论】:
-
从命令提示符运行脚本,看看它是否仍然返回 Explorer.exe 作为前台窗口。
-
它返回了运行它的提示的PID。
-
那么这里的目标是什么?
-
我非常希望有一个键盘快捷键,当按下它时,将当前进程(例如,假设我正在对 Chrome 进行一些研究,然后它将存储浏览器的 PID)存储在内存中,并且切换到powershell。然后,当再次按下时,切换回存储过程。我的方法是编写这个脚本,然后创建一个调用它的键盘快捷键。
标签: powershell