//--列举IE全部Element的代码
#include "stdafx.h"
#pragma warning(disable : 4049) #pragma warning(disable : 4192) #pragma warning(disable : 4146)
//#import "shdocvw.dll" exclude("tagREADYSTATE") #import "shdocvw.dll" //#import "shdocvw.dll" rename_namespace("SHELL_WINDOW") //using namespace SHELL_WINDOW; #define SHELL_WINDOW SHDocVw
#include <atlbase.h> #include <comdef.h> #include <MSHTML.H>
#include <iostream> using namespace std;
int IElement(IHTMLDocument2Ptr sp_Doc) { int ret = 0; CComPtr<IHTMLElementCollection> pCollection;
do {
cout << "---list all IE Element---" << endl; //--FAILED //if (!SUCCEEDED(sp_Doc->get_links(&pCollection))) if (!SUCCEEDED(sp_Doc->get_all(&pCollection)))
{ cout << "FAILED." << endl; break; }
int count = 0; int Count = 0; if (!SUCCEEDED(pCollection->get_length((long*)&Count))) { cout << "FAILED." << endl; break; }
for (int i = 0; i < Count; i++) { _variant_t index = long(i);
CComPtr<IDispatch> spDispatch; if (SUCCEEDED(pCollection->item(index, index, &spDispatch))) { CComPtr<IHTMLElement> pElement; if (SUCCEEDED(spDispatch->QueryInterface( __uuidof(IHTMLElement), (void **)&pElement))) { count ++; CComBSTR bstr;
pElement->get_tagName(&bstr); if (bstr.Length() > 0) cout << "tag=" << (char*)_bstr_t(bstr);// << endl;
pElement->get_innerText(&bstr); if (bstr.Length() > 0) cout << "\ttext=" << (char*)_bstr_t(bstr) << endl; else cout << "\ttext=" << endl;
pElement->toString(&bstr); if (bstr.Length() > 0) cout << "str=" << (char*)_bstr_t(bstr) << endl;
//pElement->Release(); } //spDispatch->Release(); } } //pCollection->Release(); cout << "---list count=" << count << "|" << Count << "---" << endl;
ret = count; break;
} while (false);
return ret; }
int main(int argc, char* argv[]) { cout << "---test---" << endl; //--COM CoInitialize(NULL); do { cout << "---list all IE Window---" << endl;
SHELL_WINDOW::IShellWindowsPtr msp_SHWinds = NULL; HRESULT hr = msp_SHWinds.CreateInstance(__uuidof(SHELL_WINDOW::ShellWindows)); if (S_OK != hr || NULL == msp_SHWinds) { cout << "FAILED." << endl; break; } int count = 0; int Count = msp_SHWinds->GetCount(); for (int i = 0; i < Count; i++) { _variant_t va(long(i), VT_I4); IDispatchPtr sp_Disp; sp_Disp = msp_SHWinds->Item(va); //SHELL_WINDOW::IWebBrowser2Ptr sp_Browser = sp_Disp;//--OK SHELL_WINDOW::IWebBrowser2Ptr sp_Browser(sp_Disp); if (NULL != sp_Browser) { //cout << (char*)sp_Browser->GetLocationName() << endl;
IHTMLDocument2Ptr sp_Doc(sp_Browser->GetDocument()); if (NULL != sp_Doc) { count ++;
CComBSTR bstr; sp_Doc->get_title(&bstr); cout << (char*)_bstr_t(bstr) << endl;
static int e = 0; if (0 == e) e = IElement(sp_Doc); sp_Doc.Release(); }
sp_Browser.Release(); } } msp_SHWinds.Release();
cout << "---list count=" << count << "---" << endl; break; } while (false); //--COM //CoUninitialize();//--??? OleUninitialize(); return 0; }

|