这里总的vbs脚本新手。我试图自动关闭某个打开的窗口,即一个名为HostsMan的程序。这是在Windows 8.1 Pro 64位上,这是我的脚本目前的样子:
Set WshShell = CreateObject("WScript.Shell")
WshShell.AppActivate "HostsMan"
WshShell.SendKeys "%{F4}"
第二行似乎不起作用。我知道第3行有效,因为它激活了Windows关闭菜单。我有什么遗失的吗?
更新/更多信息:手动输入alt-F4会关闭它,所以我知道这应该有效。我还用其他打开的窗口测试了这个脚本,它们关闭得很好。此外,HostsMan以管理员权限打开,因此我尝试将脚本作为具有最高权限的任务集运行,以查看是否会执行此操作,但仍然没有。但这适用于使用Admin权限运行的其他打开的窗口。令人沮丧!
答案 0 :(得分:10)
我也试过了,并且无法让它发挥作用。也许,窗口类必须有一些东西,AppActivate
没有将它视为顶级窗口?
无论如何,AppActivate
还允许您传递进程ID而不是窗口标题。当我安装HostsMan时,进程名称为hm.exe
,因此我将在下面的示例中使用它。
Set Processes = GetObject("winmgmts:").InstancesOf("Win32_Process")
For Each Process In Processes
If StrComp(Process.Name, "hm.exe", vbTextCompare) = 0 Then
' Activate the window using its process ID...
With CreateObject("WScript.Shell")
.AppActivate Process.ProcessId
.SendKeys "%{F4}"
End With
' We found our process. No more iteration required...
Exit For
End If
Next
答案 1 :(得分:3)
要解决 AppActivate
的问题,您必须使用循环以及条件语句来检查活动窗口是否是目标窗口,因为有时您取消选择或系统取消选择了目标窗口,然后直接执行sendkeys,所以会出错。
我创建了这种严格的严格方法
Set WshShell = CreateObject("WScript.Shell")
for i=0 to 300 ' this loop will continue about 30 sec if this not enough increase this number
Rtn=WshShell.AppActivate("HostsMan") ' HostMan have to be the windows title of application or its process ID
If Rtn = True Then
WshShell.SendKeys "%{F4}" ' send key to click ALT+F4 to close
wscript.sleep 100 ' stop execute next line until finish close app
Rtn=WshShell.AppActivate("HostsMan")
If Rtn=False Then ' using nested If to sure of selected windows is false because its close
Exit For ' exit for loop directly and execute what after for next
End If
End If
wscript.sleep 100
Next
答案 2 :(得分:1)
这里的关键是在'run'命令之后但在'appactivate'命令之前放一个小暂停,以便应用程序显示在进程列表中。
WshShell.Run "calc"
WScript.Sleep 100
WshShell.AppActivate "Calculator"
答案 3 :(得分:0)
使用WMIService的替代解决方案(无需遍历所有需要的流程):
Set objWMIService = GetObject("winmgmts:\\" & strComputer & "\root\CIMV2")
Set colItems = objWMIService.ExecQuery("SELECT * from Win32_Process WHERE Name = '" & ProcessName & "'")
If colItems.Count = 0 Then
WScript.Echo "Process not found"
Wscript.Quit
End If
For Each objProcess in colItems
WshShell.AppActivate(objProcess.ProcessId)
Exit For
Next
答案 4 :(得分:0)
Dim sh : Set sh =CreateObject("Wscript.Shell")
sh.Exec "calc.exe"
Wscript.Sleep 1000
sh.Exec "taskkill /f /FI ""WINDOWTITLE eq ""calc*"""
OR
sh.Run "taskkill /f /im calc.exe",0,False