楼主 xmyjk |
Q:如何用VBA获取IE浏览器弹出的alert窗口的提示消息? 如下图所示图片和网页源代码:
- <html>
- <body onload = alert("wahaaaaaaaaaaaaaaa")>
- 我是演示文档**
- </body>
- </html>
A:思路分析:抓取网页的警告框的句柄,然后历遍其二级窗口(详情百度window窗口结构),提取文本,最后发送确认键。 注意:如上图,我的IE的弹出警告窗的标题栏是Windows Internet Explorer(一般为Windows Internet Explorer;来自网页的消息;安全警报;安全警告等等),请按情况修改下面的代码“hWnd = FindWindowEx(0&, 0&, vbNullString, ByVal "Windows Internet Explorer")这句”。- Private Declare Function FindWindowEx Lib "user32" Alias "FindWindowExA" (ByVal hWnd1 As Long, ByVal hWnd2 As Long, ByVal lpsz1 As String, ByVal lpsz2 As Any) As Long 'API抓窗口函数
- Private Declare Function GetWindowText Lib "user32" Alias "GetWindowTextA" (ByVal hWnd As Long, ByVal lpString As String, ByVal cch As Long) As Long 'api取窗口文本函数
- Option Explicit
- Sub t()
- Dim hWnd&, i%, AllWndText$, fhwnd&
- With CreateObject("InternetExplorer.Application") '创建IE对象
- .Visible = True '可视
- .Navigate ThisWorkbook.Path & "\1111.html" '激活网页
- Do Until .ReadyState = READYSTATE_COMPLETE '待加载完毕
- DoEvents
- Loop
- hWnd = FindWindowEx(0&, 0&, vbNullString, ByVal "Windows Internet Explorer") '抓取弹出警告框窗口
- Dim wndtext$
- wndtext = Space(512) '设置提取的文本变量
- fhwnd = hWnd
- hWnd = FindWindowEx(fhwnd, 0&, vbNullString, 0&) '寻找母窗口下级窗口
- Do While hWnd > 0 '历遍
- i = GetWindowText(hWnd, wndtext, 512) '取文本
- If i Then AllWndText = AllWndText & Left(wndtext, i) & "-"
- hWnd = FindWindowEx(fhwnd, hWnd, vbNullString, 0&) '继续历遍下个同级窗口
- Loop
- [a2] = Replace(AllWndText, Chr(0), "") '输出
- SendKeys "~" '关闭弹出窗口
- End With
- End Sub
注意,附件要下到硬盘加压缩运行。 弹出消息窗截取.zip |