You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何实现监听应用启停并关联进程终止?批处理及替代方案求助

当然可以实现!我刚好处理过类似的进程依赖监听需求,不管是批处理还是PowerShell都能搞定,下面分两种方案给你详细说明:

批处理解决方案

这种方案完全基于原生Windows批处理,不需要额外工具,适合习惯用.cmd/.bat脚本的场景:

@echo off
setlocal enabledelayedexpansion

:: 1. 启动Hearthstone Beta Launcher
start "" "D:\...\Hearthstone Beta Launcher.exe"
:: 2. 启动Innkeeper
start "" "C:\...\Innkeeper.exe"

:: 3. 循环等待Hearthstone.exe启动(每5秒检测一次)
echo 等待Hearthstone启动中...
:WAIT_FOR_HS
timeout /t 5 /nobreak >nul
tasklist /fi "imagename eq Hearthstone.exe" | find /i "Hearthstone.exe" >nul
if errorlevel 1 goto WAIT_FOR_HS
echo Hearthstone已启动!

:: 4. 监听Hearthstone.exe,直到它关闭
echo 正在监听Hearthstone进程...
:WAIT_FOR_HS_CLOSE
timeout /t 3 /nobreak >nul
tasklist /fi "imagename eq Hearthstone.exe" | find /i "Hearthstone.exe" >nul
if not errorlevel 1 goto WAIT_FOR_HS_CLOSE
echo Hearthstone已关闭,开始清理相关进程...

:: 5. 强制终止Innkeeper和Battle.net客户端(适配不同进程名)
taskkill /f /im Innkeeper.exe >nul 2>&1
taskkill /f /im Battle.net.exe >nul 2>&1
taskkill /f /im "Battle.net Launcher.exe" >nul 2>&1

echo 所有关联进程已终止!
:: 6. 退出脚本
endlocal
exit

关键细节说明:

  • setlocal enabledelayedexpansion:启用延迟变量扩展,确保循环逻辑稳定(即使本脚本没用到变量,也是批处理脚本的好习惯)
  • 两个timeout命令:控制检测间隔,避免过度占用系统资源,你可以根据需求调整秒数
  • >nul 2>&1:屏蔽进程不存在时的错误提示,让控制台输出更干净
  • Battle.net的进程名可能因版本不同变化,你可以打开任务管理器确认后调整taskkill的目标
PowerShell替代方案

如果你想要更高效、更简洁的实现,PowerShell的进程API会更顺手:

# 1. 启动Hearthstone Beta Launcher和Innkeeper
Start-Process "D:\...\Hearthstone Beta Launcher.exe"
Start-Process "C:\...\Innkeeper.exe"

# 2. 等待Hearthstone.exe启动
Write-Host "等待Hearthstone启动中..."
do {
    Start-Sleep -Seconds 5
    $hsProcess = Get-Process -Name Hearthstone -ErrorAction SilentlyContinue
} while (-not $hsProcess)
Write-Host "Hearthstone已启动!"

# 3. 等待Hearthstone进程自然退出(原生API,无需轮询)
$hsProcess.WaitForExit()
Write-Host "Hearthstone已关闭,开始清理进程..."

# 4. 终止Innkeeper和所有Battle.net相关进程
Get-Process -Name Innkeeper -ErrorAction SilentlyContinue | Stop-Process -Force
Get-Process -Name "Battle.net*" -ErrorAction SilentlyContinue | Stop-Process -Force

Write-Host "所有关联进程已终止!"

PowerShell方案优势:

  • $hsProcess.WaitForExit():原生的进程等待方法,比批处理的定时轮询更高效,不会浪费系统资源
  • 通配符Battle.net*:一次性匹配所有Battle.net相关进程,不用逐个找进程名
  • -ErrorAction SilentlyContinue:避免因进程不存在抛出错误,脚本容错性更强

注意事项:

不管用哪种方案,都记得把脚本里的D:\...\Hearthstone Beta Launcher.exe和C:\...\Innkeeper.exe替换成你实际的文件路径哦!

内容的提问来源于stack exchange,提问作者Mate de Vita

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 08:07:20