Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

WshShell.AppActivate doesn't seem to work in simple vbs script

total vbs scripting newb here. I'm trying to automate closing a certain open window, namely a program called HostsMan. This is on Windows 8.1 Pro 64 bit, and this is what my script currently looks like:

Set WshShell = CreateObject("WScript.Shell")
WshShell.AppActivate "HostsMan"
WshShell.SendKeys "%{F4}"

The second line doesn't seem to work. I know line 3 works because it activates the Windows shutdown menu. Is there something I'm missing?

Update/more info: Manually entering alt-F4 does close it, so I know this should work. I also tested this script with other open windows and they close just fine. Additionally, HostsMan is opened with Admin privileges, so I tried running the script as a task set with highest privileges to see if that would do it, and still no go. But that does work with other open windows running with Admin privileges. Frustrating!

like image 959
user3550756 Avatar asked Apr 19 '14 03:04

user3550756


Video Answer


3 Answers

Alternative solution using WMIService (no loop through all processes required):

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
like image 190
Thierry Dalon Avatar answered Oct 12 '22 21:10

Thierry Dalon


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
like image 12
Bond Avatar answered Oct 12 '22 22:10

Bond


The key here is to put a small pause after the 'run' command but before the 'appactivate' command so the application shows up in the process list.

     WshShell.Run "calc"
     WScript.Sleep 100
     WshShell.AppActivate "Calculator"
like image 1
Jim Avatar answered Oct 12 '22 21:10

Jim