This helped me a great deal, but I found that I needed to add a small amount of time to allow the OS to actually put that window into focus, so I added WScript.Sleep 100
between the AppActivate
and SendKeys
lines.
Which worked well enough until I realized that in certain circumstances some of my processes had exited before the script was called, causing my keystrokes to be sent to the wrong window. See, the problem is that Shell.AppActivate
will send the command to activate a program by it's PID, but there's nothing to check to see if that program has exited. So, I added another sub that queried winmgmts for the active PID (as well as the CommandLine since each process is called uniquely).
Here is my contribution, with my deepest thanks:
'================
Sub DelayedSendKeysWithFocusAndProcessCheck(str, procid, cmdline)
Call ProcCheck(procid, cmdline)
Shell.AppActivate procid
WScript.Sleep 100
Shell.SendKeys str
End Sub
'================
Sub ProcCheck(procid, cmdline)
CheckedPID = ""
CheckedCmdLine = ""
Set ProcessCollection = GetObject("winmgmts:\\" & ComputerName & "\roo" &_
"t\cimv2")
Set ProcessResults = ProcessCollection.ExecQuery(" Select * from Win32_Pr" &_
"ocess where ProcessID = '" & procid & "'")
For Each obj in ProcessResults
CheckedPID = obj.ProcessID
CheckedCmdLine = obj.CommandLine
Next
If CheckedPID <> procid Then
Shell.Popup "PID " & procid & " (" & cmdline & ") appears to have exite" &_
"d!", 0, "Called Process is Missing!", vbOkOnly
Call EndScript
Else
Call RegExSearch(cmdline, CheckedCmdLine)
If ReturnValue(0) <> "" Then
Shell.Popup "The PID " & procid & " no longer shows the same command " &_
"line I started it with!" & vbcrlf & "When I started it, it used " & vbcrlf &_
cmdline & vbcrlf & "Now it shows " & CheckedCmdLine & "I'm going to exit no" &_
"w. You can try to run me again or simply open the windows manually." & vbcrlf &_
"(Please note that this is an incredibly rare error and you should probabl" &_
"y buy a lottery ticket.)", 0, "Called process command line has changed!", vbOkOnly
Call EndScript
End If
End If
End Sub
'================