Search code examples
vbscriptfocussendkeyswsh

Ensure window focus before sending keys


I'm using a VBScript to SendKeys to a Cisco Client because it prompts for a username and password. However, I am having problems getting the command prompt focused.

I added AppActivate before every SendKeys command, but normal computer usage often breaks the focus in the time between these commands.

How can I ensure the command prompt has focus before sending keys?

Dim host, username, password, pathToClient
host = "host"
username = "username"
password = "password"
pathToClient = "C:\Program Files {(}x86{)}\Cisco\Cisco AnyConnect Secure Mobility Client\vpncli.exe"

Set ws = WScript.CreateObject("WScript.Shell")
ws.run("TASKKILL.exe /F /IM vpnui.exe"), 0, false
ws.run("cmd.exe"), 2, false
WScript.Sleep 300
ws.AppActivate("Command Prompt")
ws.SendKeys """" & pathToClient & """ connect " & host & "~"
WScript.Sleep 1000
ws.AppActivate("Command Prompt")
ws.SendKeys(username & "~")
WScript.Sleep 50
ws.AppActivate("Command Prompt")
ws.SendKeys(password & "~")
ws.run("TASKKILL.exe /F /IM cmd.exe"), 0, false

Solution

  • I used AutoHotKey to solve my issue. Here's my code:

    host := "my.host.domain"
    username := "myUsername"
    password := "myPassword"
    pathToClient = "C:\...\vpncli.exe"
    
    DetectHiddenWindows, on
    Process, Close, vpnui.exe
    run, cmd.exe,, Hide
    Sleep 100
    ControlSend,, %pathToClient% connect %host%{Enter}, ahk_exe cmd.exe
    Sleep 1000
    ControlSend,, %username%{Enter}, ahk_exe cmd.exe
    Sleep 50
    ControlSend,, %password%{Enter}, ahk_exe cmd.exe
    ;Process, Close, cmd.exe