網頁 <input type="text/password"> 無視窗控制代碼,無法用 GetWindowText 取值。透過 ShellWindows 列舉 IE 實例,取得 IHTMLDocument2,遞迴遍歷 forms 集合中的 IHTMLInputTextElement 即可讀取所有文字框與密碼框的值。
CoInitialize;ShellWindows 列舉開啟的 IE 視窗(IWebBrowser2)。get_Document 取得 IDispatch,QueryInterface 為 IHTMLDocument2。get_forms 取得 IHTMLElementCollection,遍歷每個 form。form->get_length 取得元素數,遍歷每個元素 QueryInterface 為 IHTMLInputTextElement。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)。