Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AppActivate doesn't always activate the application window

So I'm working on some VBScript that will automate Internet Explorer: Open it, navigate, and download a file. I've got it working, however there's an issue that lies with the fact that I need to send keystrokes to it. SendKeys is working for me, but the problem is that when I use AppActivate to set focus on IE, it doesn't always work. Basically it can fall into these two cases:

Case 1: Double-click my .vbs file and the automation process goes smoothly. Window is activated and everything works fine.

Case 2: Double-click my .vbs file and some other app opens a window that steals focus (or manually click something else to change focus). When the AppActivate line is executed later on, IE never gets focused and the keystrokes obviously don't go through.

So do you guys have any ideas on why AppActivate isn't setting focus?

Here's the code I'm using to activate the IE window:

Do While Not wshell.AppActivate("Active Agents - Internet Explorer")
    WScript.Sleep(1)
Loop
like image 297
Steven Avatar asked Aug 03 '16 16:08

Steven


1 Answers

This script example of running IE and send keys with AppActivate focus

    'fuction to set the application active and then send keys 
    Function mySendKey(sKey,sTime)
       for i=0 to 600        ' this loop will continue about 30 sec if this not enough increase this number
        'get the window title of the IE
        title= sh.Exec("cmd.exe /c tasklist /v /fi ""imagename EQ iexplore*"" /FO LIST | FIND /i ""window title:"" ").stdOut.readline
        title= Mid (title,15,len(title)-14)
        sh.Popup  title,1

        Sh.AppActivate title
        Rtn=Sh.AppActivate(title)     '  window title of application
        If Rtn = True  Then           'if the window active then execute sned keys
            Sh.SendKeys  sKey                                     
            Exit For 
        End If
        wscript.sleep 10                              
      Next
     WScript.Sleep sTime*1000
    End Function

  'hide the cmd window from popup 
  If StrComp(right(WScript.FullName,11),"wscript.exe",1) = 0 Then    
  WScript.Quit CreateObject("WScript.Shell").Run("cscript.exe //nologo """ & WScript.ScriptFullName & """", 0, False)
  End If 
  'open internet explorer   
Set Sh = CreateObject("WScript.Shell")
Sh.Exec "C:\Program Files\Internet Explorer\iexplore.exe"
WScript.Sleep 7000
 'call mySendKey function to send keys to IE  
 Call mySendKey("(% )(x)",1)                         'max the windows of IE
 Call mySendKey("({F6})(www.yahoo.com)    (~)",10)   'browse to yahoo and wait 10 sec to load
 Call mySendKey("({F6})(www.msn.com)      (~)",10)   'browse to msn and wait 10 sec to load 
 Call mySendKey("(% )(C)",1)                         'close the IE
like image 120
hollopost Avatar answered Oct 20 '22 14:10

hollopost