本文目录导读:

Windows 环境
PowerShell 脚本
$windowTitle = "计算器" # 替换为目标窗口标题
$processes = Get-Process | Where-Object { $_.MainWindowTitle -eq $windowTitle }
$processes | Stop-Process -Force
# 或者使用任务管理器命令
taskkill /FI "WINDOWTITLE eq 计算器" /F
# 按进程名终止
taskkill /IM notepad.exe /F
VBScript 脚本
' 创建脚本文件 .vbs
Set objShell = CreateObject("Shell.Application")
objShell.Windows().Item(0).Quit ' 关闭特定窗口
Linux/Unix 环境
Bash 脚本
#!/bin/bash终止
window_title="Firefox"
wmctrl -l | grep "$window_title" | awk '{print $1}' | xargs -I {} wmctrl -i -c {}
# 使用 xdotool
xdotool search --name "$window_title" windowkill
# 按进程名
pkill -f firefox
Python 脚本(跨平台)
import subprocess
import sys
def kill_window_by_title(title):
if sys.platform == "win32":
# Windows
subprocess.run(['taskkill', '/F', '/FI', f'WINDOWTITLE eq {title}'])
else:
# Linux
subprocess.run(['wmctrl', '-l']
if not subprocess.run(['which', 'wmctrl'],
capture_output=True).returncode
else ['echo', '需要安装wmctrl'])
# 使用示例
kill_window_by_title("My Application")
批处理脚本(Windows)
@echo off
:: 查找并终止特定窗口
for /f "tokens=2" %%a in ('tasklist ^| findstr "notepad.exe"') do (
taskkill /PID %%a /F
)
:: 或使用窗口标题
taskkill /FI "WINDOWTITLE eq 计算器" /F
自动化测试框架
Selenium(Web窗口)
from selenium import webdriver driver = webdriver.Chrome() # 关闭特定窗口 driver.switch_to.window(driver.window_handles[0]) driver.close()
AutoHotkey(Windows)
; 关闭指定标题的窗口 WinClose, 计算器
使用建议
- 精确匹配:使用完整的窗口标题避免误杀
- 权限问题:可能需要管理员权限
- 安全提醒:强制终止可能导致数据丢失
选择哪种方法取决于你的操作系统和使用场景,需要我详细解释某个具体方案吗?