Joel Christophel
Joel Christophel

Reputation: 2663

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

Upvotes: 0

Views: 1014

Answers (2)

Joel Christophel
Joel Christophel

Reputation: 2663

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

Upvotes: 0

Ansgar Wiechers
Ansgar Wiechers

Reputation: 200293

With VBScript you can't. AppActivate is the only method available in VBScript to place the focus on a particular application, and it doesn't ensure the focus stays there. That's the exact reason why SendKeys shouldn't be used for automation anyway. Try something like AutoIt instead.

Or might setting Auto Connect on Start be an option, since you're apparently using AnyConnect?

Auto Connect on Start—AnyConnect, when started, automatically establishes a VPN connection with the secure gateway specified by the AnyConnect profile, or to the last gateway to which the client connected.

Upvotes: 1

Related Questions