首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> C語言 >> VC >> 關於VC++

枚舉 IE 開啟網頁中所有表單輸入框內容:基於 IHTMLInputTextElement 的 VC++ 實作

     編輯:關於VC++

網頁 <input type="text/password"> 無視窗控制代碼,無法用 GetWindowText 取值。透過 ShellWindows 列舉 IE 實例,取得 IHTMLDocument2,遞迴遍歷 forms 集合中的 IHTMLInputTextElement 即可讀取所有文字框與密碼框的值。

核心實作步驟

  1. CoInitialize;ShellWindows 列舉開啟的 IE 視窗(IWebBrowser2)。
  2. get_Document 取得 IDispatch,QueryInterface 為 IHTMLDocument2。
  3. get_forms 取得 IHTMLElementCollection,遍歷每個 form。
  4. form->get_length 取得元素數,遍歷每個元素 QueryInterface 為 IHTMLInputTextElement。
  5. get_type 判斷 "text" 或 "password",get_value 取得內容。

關鍵代碼片段

SHDocVw::IShellWindowsPtr spSHWinds(__uuidof(SHDocVw::ShellWindows));
long nCount = spSHWinds->GetCount();
for (long i = 0; i < nCount; ++i) {
    _variant_t vIdx(i); IDispatchPtr spDisp = spSHWinds->Item(vIdx);
    SHDocVw::IWebBrowser2Ptr spBrowser(spDisp);
    if (!spBrowser) continue;

    IDispatchPtr spDocDisp; spBrowser->get_Document(&spDocDisp);
    CComQIPtr<IHTMLDocument2> pDoc2(spDocDisp); if (!pDoc2) continue;

    CComPtr<IHTMLElementCollection> spForms; pDoc2->get_forms(&spForms);
    long formCnt = 0; spForms->get_length(&formCnt);
    for (long f = 0; f < formCnt; ++f) {
        CComVariant id(f), index(0); IDispatchPtr spFormDisp;
        spForms->item(id, index, &spFormDisp);
        CComQIPtr<IHTMLFormElement> pForm(spFormDisp); if (!pForm) continue;

        long elemCnt = 0; pForm->get_length(&elemCnt);
        for (long e = 0; e < elemCnt; ++e) {
            CComVariant id2(e), index2(0); IDispatchPtr spElemDisp;
            pForm->item(id2, index2, &spElemDisp);
            CComQIPtr<IHTMLInputTextElement> pInput(spElemDisp);
            if (!pInput) continue;

            CComBSTR type, val; pInput->get_type(&type); pInput->get_value(&val);
            CString strType(type); strType.MakeUpper();
            if (strType.Find(_T("TEXT")) >= 0) { /* 文字框 */ }
            else if (strType.Find(_T("PASSWORD")) >= 0) { /* 密碼框 */ }
        }
    }
}
CoUninitialize();

注意事項

  • 需引用 MSHTML.tlb 與 SHDocVw.tlb(或 #import)。
  • 框架代碼參考《如何控制 IE 的行為》一文,核心遍歷邏輯為原創。
  • 僅適用於 Internet Explorer;Edge/Chrome 無法使用。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved