如何编写PowerShell脚本定时Alt+Tab切换到指定应用窗口
按进程名/窗口名定时切换到指定应用窗口的PowerShell方案
你原来的脚本依赖SendKeys模拟Alt+Tab,这种方式只能在最近的两个窗口间循环,无法精准定位目标应用。要实现按进程名或窗口名切换,需要调用Windows原生API来查找并激活目标窗口,以下是完整实现:
完整脚本
# 引入Windows API所需类型 Add-Type @" using System; using System.Runtime.InteropServices; public class WindowHelper { [DllImport("user32.dll", SetLastError = true)] public static extern IntPtr FindWindow(string lpClassName, string lpWindowName); [DllImport("user32.dll", SetLastError = true)] public static extern bool SetForegroundWindow(IntPtr hWnd); [DllImport("user32.dll")] public static extern bool ShowWindow(IntPtr hWnd, int nCmdShow); [DllImport("user32.dll")] public static extern uint GetWindowThreadProcessId(IntPtr hWnd, out uint lpdwProcessId); } "@ # 自定义配置参数 $targetWindowTitle = "计算器" # 目标窗口的完整标题(可替换为你的应用标题) $targetProcessName = "calc.exe" # 目标进程名(二选一即可,优先匹配窗口标题) $intervalSeconds = 5 # 切换间隔时间(单位:秒) # 获取目标窗口句柄的函数 function Get-TargetWindowHandle { param( [string]$WindowTitle, [string]$ProcessName ) # 优先通过窗口标题查找 if (-not [string]::IsNullOrEmpty($WindowTitle)) { $hwnd = [WindowHelper]::FindWindow($null, $WindowTitle) if ($hwnd -ne [IntPtr]::Zero) { return $hwnd } } # 窗口标题找不到时,通过进程名查找主窗口 if (-not [string]::IsNullOrEmpty($ProcessName)) { $process = Get-Process -Name $ProcessName.Replace(".exe", "") -ErrorAction SilentlyContinue if ($process -and $process.MainWindowHandle -ne [IntPtr]::Zero) { return $process.MainWindowHandle } } return [IntPtr]::Zero } # 循环执行切换逻辑 while ($true) { $targetHwnd = Get-TargetWindowHandle -WindowTitle $targetWindowTitle -ProcessName $targetProcessName if ($targetHwnd -ne [IntPtr]::Zero) { # 若窗口处于最小化状态,先还原 [WindowHelper]::ShowWindow($targetHwnd, 9) # 9对应SW_RESTORE常量 # 将窗口激活为前台窗口 [WindowHelper]::SetForegroundWindow($targetHwnd) } else { Write-Warning "未找到目标窗口或进程,请检查配置参数" } Start-Sleep -Seconds $intervalSeconds }
关键说明
- API调用逻辑:通过
user32.dll提供的FindWindow(按标题找窗口)、SetForegroundWindow(激活窗口)、ShowWindow(还原最小化窗口)实现精准控制,替代原有的模拟按键方案。 - 参数配置:
- 可以只填写
$targetWindowTitle或$targetProcessName任意一个,脚本会优先匹配窗口标题 - 修改
$intervalSeconds调整切换间隔
- 可以只填写
- 模糊匹配窗口标题:如果需要匹配包含关键词的窗口标题,可修改
Get-TargetWindowHandle函数中的窗口查找逻辑为:# 模糊匹配窗口标题示例 $matchingProcesses = Get-Process | Where-Object { $_.MainWindowTitle -like "*关键词*" } if ($matchingProcesses) { return $matchingProcesses[0].MainWindowHandle } - 权限注意:部分系统级应用或管理员权限运行的进程,需要以管理员身份启动PowerShell才能正常获取窗口句柄。
内容的提问来源于stack exchange,提问作者Nasty Earl
相关产品推荐
相关产品推荐

