Visual C++ 7.1Visual C++ 7.0Windows 2003Windows 2000Visual C++ 6.0Windows XPMFC中级开发Visual StudioWindowsC++
使用 IWebBrowser2 连接 Gmail






1.78/5 (5投票s)
2004 年 6 月 17 日
1分钟阅读

76855
使用 IWebBrowser2 连接 Gmail
引言
当我注册 Gmail 账户时,我必须执行许多复杂的步骤才能登录 Gmail 系统。 我认为,如果有一个像 POP# 这样的接口,人们会觉得使用 Gmail 系统更加方便。
我不知道 Gmail 客户端 API,所以我使用 IE COM 接口来管理 IE,以完成我们手动执行的操作。
有很多关于 IE 编程的文章,但我找不到一个可以处理包含框架或 IFrame 的页面的代码。 在本文中,我解决了这个问题。
首先,我们可以使用 get_frames
来获取框架集合。 如果页面没有 <body> 标签,则框架集合将包含所有框架集。 否则,框架集合将包含所有 iframe。 在 Gmail 登录页面中,有一个 iframe 标签,我们可以找到它并获取表单。
BOOL CGMailClass::lunchBrowser() { HRESULT hr1 ; hr1 = CoInitialize(NULL); if(!SUCCEEDED(hr1)) return FALSE; //Create an Instance of web browser hr1 = CoCreateInstance (CLSID_InternetExplorer, NULL, CLSCTX_LOCAL_SERVER, IID_IWebBrowser2, (LPVOID *)&m_pBrowser); if(hr1==S_OK) { VARIANT_BOOL pBool=true; //The browser is invisible m_pBrowser->put_Visible( pBool ) ; //Gmail login page COleVariant vaURL("https://gmail.google.com/gmail") ; COleVariant null; //Open the mail login page m_pBrowser->Navigate2(vaURL,null,null,null,null) ; WaitForEnd(); } return TRUE; }m_pBrowser 是这个类的成员变量,声明如下:
protected:
IWebBrowser2* m_pBrowser;
下面的函数用于从 IFrame 获取文档,以便我们可以找到表单元素。BOOL CGMailClass::getDoc(IHTMLDocument2** pIFrameDoc) { IDispatch *spDispatch; CComQIPtrgetForm 函数可以获取表单元素,然后可以使用该表单元素来设置输入值、可见性和其他属性。pDoc2; if (m_pBrowser){ spDispatch=NULL; if (SUCCEEDED(m_pBrowser->get_Document( &spDispatch))) pDoc2 = spDispatch; if(pDoc2!=NULL) { //because the Gmail login page hide in a Iframe //so we must find where is the IFrame object CComPtr pIFrameCol; if (SUCCEEDED(pDoc2->get_frames(&pIFrameCol))) { //retreive all of the Frames long p=0; pIFrameCol->get_length(&p); if(p!=0) { //yes we find more than one Frames for(long i=0;i<=(p-1);i++) { VARIANT frameRequested; VARIANT frameOut; frameRequested.vt = VT_I4 ; frameRequested.bstrVal = (BSTR)i; pIFrameCol->item(&frameRequested, &frameOut); IHTMLWindow2* pIFrameWindow; frameOut.pdispVal->QueryInterface(IID_IHTMLWindow2, (void**)&pIFrameWindow); pIFrameWindow->get_document(pIFrameDoc); return TRUE; //ParseDoc(pIFrameDoc); } } } } } return FALSE; }
BOOL CGMailClass::getForm(IHTMLDocument2 *pIFrameDoc, IHTMLFormElement **pFormElement) { IHTMLElementCollection* pElementCol=NULL; long p=0; if (SUCCEEDED(pIFrameDoc->get_forms(&pElementCol))) { if(SUCCEEDED(pElementCol->get_length(&p))) if(p!=0) { for(long i=0;i<=(p-1);i++) { VARIANT id, index; IDispatch* spDispatch=NULL; V_VT(&id) = VT_I4; V_I4(&id) = i; V_VT(&index) = VT_I4; V_I4(&index) = 0; spDispatch=NULL; if(SUCCEEDED(pElementCol->item(id,index, &spDispatch))) { if(SUCCEEDED(spDispatch->QueryInterface( IID_IHTMLFormElement,(void**)pFormElement))) return TRUE; } } } } return FALSE; }
在这个演示中,我只实现了登录功能,因为 Gmail 系统使用了太多且过于复杂的 JavaScript。 我找不到获取收件箱属性的方法。 如果您有好的方法,请告诉我。 您可以通过 mailto:ChineseDofu@gmail.com 联系我。
我必须感谢 pratheesh,因为他的 Yahoo Mail。