我知道这可以通过使用alt-tab轻松完成,但是这个脚本创建的主要目的是教自己一些PowerShell基础知识。
我正在编写一个脚本,在运行时切换PowerShell和当前前景窗口之间的前景窗口。我阅读this question并使用其中一个答案获取用于检索当前前景窗口的代码,但它似乎没有抓住正确的窗口 - 它似乎抓住了explorer.exe
下面是我的脚本代码,希望有用的评论:
# 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作为“前景窗口”,因为我通过一个从资源管理器启动的快捷方式调用脚本。
答案 0 :(得分:0)
尝试使用此方法获取您喜欢的进程的ID或以您喜欢的任何其他方式获取它。
Add-Type @"
using System;
using System.Runtime.InteropServices;
public class Tricks {
[DllImport("user32.dll")]
public static extern IntPtr GetForegroundWindow();
}
"@
$a = [tricks]::GetForegroundWindow()
$WH = get-process | ? { $_.mainwindowhandle -eq $a }
现在,假设您的活动窗口是另一个窗口,并且您想回到与$WH
相关的窗口。只需使用following code返回到它即可。您可以使用任意喜欢的触发器来做到这一点,就像您通过键盘热键提到的那样或自动进行。
$sig = '
[DllImport("user32.dll")] public static extern bool ShowWindowAsync(IntPtr hWnd, int nCmdShow);
[DllImport("user32.dll")] public static extern int SetForegroundWindow(IntPtr hwnd);
'
$type = Add-Type -MemberDefinition $sig -Name WindowAPI -PassThru
# maximize the window related to $WH; feel free to play with the number
$null = $type::ShowWindowAsync($WH, 4)
# change the focus to $WH
$null = $type::SetForegroundWindow($WH)