总vbs脚本newb在这里。 我试图自动closures某个打开的窗口,即一个名为HostsMan的程序。 这是在Windows 8.1 Pro 64位,这是我的脚本目前的样子:
Set WshShell = CreateObject("WScript.Shell") WshShell.AppActivate "HostsMan" WshShell.SendKeys "%{F4}"
第二行似乎不工作。 我知道第3行工作,因为它激活Windows关机菜单。 有什么我失踪?
更新/更多信息:手动inputALT-F4确实closures了,所以我知道这应该工作。 我也testing了这个脚本与其他打开的窗户,他们closures就好了。 另外,HostsMan是以pipe理员权限打开的,所以我试着把脚本作为一个具有最高权限的任务来运行,看看是否会这样做,而且还是不行。 但是,这与其他使用pipe理权限运行的打开的窗口一起工作。 令人沮丧!
我也尝试过,并且无法使用它。 有一些关于窗口类的东西,也许, 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
这里的关键是在“运行”命令之后但在“appactivate”命令之前放置一个小暂停,以便应用程序显示在进程列表中。
WshShell.Run "calc" WScript.Sleep 100 WshShell.AppActivate "Calculator"
使用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