WshShell.AppActivate doesn't seem to work in simple vbs script
I've tried it, too, and couldn't get it to work. There must be something about the window class, perhaps, where AppActivate
doesn't see it as a top-level window?
In any event, AppActivate
also lets you pass the process ID instead of the window title. When I installed HostsMan, the process name was hm.exe
, so I'll use that in my example below.
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
To solve the problem of AppActivate
you have to use loop and if condition statement to check if the active windows is the target windows or not because sometime you deselect or the system deselect the target windows before execute the sendkeys directly so you got error.
I create this tight strict way
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