JavaScript Alert()未在IE中获得焦点



我正在尝试使用VBA在IE7中自动化JavaScript表单/页面。我已经决定必须使用sendkeys来跳过JS警报弹出窗口。由于这个过程需要一些时间才能运行,所以这个函数的目的是让用户能够在后台运行这个过程并做其他事情。在使用sendkey时,这不是我的首选选项,但我不知道我还有其他选择(除了强制用户等待进程完成,我可以将其作为最后选项)。

为了防止sendkey的问题转到错误的应用程序,我将焦点强制放在当前IE窗口。这样一来,焦点就集中在IE主窗口上,而不是警报框上。如果我试图通过暂停代码来重置焦点,然后手动点击IE窗口,焦点会转到警报框。换句话说,使用代码设置焦点似乎是罪魁祸首。

我一直没有找到一种方法来捕捉警报框使用我的自动化,否则我会试图激活它上的按钮控制。

我正在使用以下代码设置焦点:

Private Declare Function SetForegroundWindow Lib "user32" (ByVal HWND As Long) As Long
Sub WaitForIE(myIEWindow As InternetExplorer, HWND As Long, Optional CheckForAlert As Boolean = False)
'OTHER CODE
    While myIEWindow.Busy
        DoEvents  ' Wait until IE is done loading page and/or user actions are done.
        Application.Wait DateAdd("s", 1, Now()) ' Wait one second per cycle so as not to use too much CPU
        If CheckForAlert Then 'Only check for alert box when certain pages are loaded
            Dim IEPage As Variant
            Dim PlaceHolder As Long
            Dim SearchFor As String
            SearchFor = "userMessage = '"
            Set IEPage = myIEWindow.Document.Frames(2).Document.Body
            PlaceHolder = InStr(IEPage.innerhtml, SearchFor)
            If PlaceHolder > 0 Then
                If InStr(PlaceHolder + Len(SearchFor), IEPage.innerhtml, "'") > PlaceHolder + Len(SearchFor) + 1 Then ' if userMessage does not equal '' then the alert will show, so clear alert box
                    SetForegroundWindow HWND 'HWND is the HWND of the myIEWindow
                    Application.SendKeys "{ENTER}", True
                End If
            End If
           Set IEPage = Nothing
        End If
    Wend
' MORE CODE
End Sub

有没有这种方法的替代方法(设置焦点),或者我缺少这种方法的另一个步骤?

诀窍是在发送{ENTER}之前发送一个{TAB},这将把焦点转移到警报框

Application.SendKeys "{TAB}{ENTER}", True

应该起作用。

最新更新