如何在 PowerShell 中获取当前活动/前景窗口

mys*_*der 6 powershell

我知道这可以通过使用 alt-tab 轻松完成,但创建此脚本的主要目的是自学一些 PowerShell 基础知识。

我正在编写一个脚本,该脚本在运行时在 powershell 和当前前台窗口之间切换前台窗口。我阅读了这个问题并使用其中一个答案来获取用于检索当前前景窗口的代码,但它似乎没有抓取正确的窗口 - 它似乎抓取了 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
}
Run Code Online (Sandbox Code Playgroud)

我在想也许我应该尝试获取活动窗口而不是前景窗口,但另一个问题的答案说前景意味着活动。

我在 Windows 10 上。

编辑:我认为它可能使用 explorer.exe 作为“前台窗口”,因为我通过从资源管理器启动的快捷方式调用脚本。

Ali*_*lin 2

尝试此方法来获取您喜欢的进程的 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 }
Run Code Online (Sandbox Code Playgroud)

现在,假设您的活动窗口是另一个窗口,并且您想返回到与 相关的窗口$WH。只需使用以下代码即可返回到它。您可以使用任何您喜欢的触发器来执行此操作,正如您提到的使用键盘热键或自动执行。

$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) 
Run Code Online (Sandbox Code Playgroud)