Search code examples
windowsvbscript

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


I am totally new to VBScript scripting. 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?

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 administrator privileges, so I tried running the script as a task set with the highest privileges to see if that would do it, and still no go. But that does work with other open windows running with administrator privileges. It is frustrating!


Solution

  • 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