通过HWND获取WebBrowser内容
2016-4-20 C++
参考资料:https://support.microsoft.com/en-us/kb/249232
已知一个窗口的HWND及窗口类为“Internet Explorer_Server",获取显示的内容!
#include <mshtml.h>
#include <atlbase.h>
#include <oleacc.h>
BOOL CALLBACK EnumChildProc(HWND hwnd, LPARAM lParam)
{
TCHAR buf[256] = { 0 };
::GetClassName(hwnd, buf, 256);
if (_tcscmp(buf, _T("Internet Explorer_Server")) == 0)
{
*(HWND*)lParam = hwnd;
return FALSE; //退出循环
}
return TRUE;
}
void GetDocInterface(HWND hWnd)
{
CoInitialize(NULL);
HINSTANCE hInst = ::LoadLibrary(_T("OLEACC.DLL");
if (hInst != NULL && hWnd != NULL)
{
HWND hWndChild = NULL;
::EnumChildWindows(hWnd, EnumChildProc, (LPARAM)&hWndChild);
if (hWndChild)
{
CComPtr<IHTMLDocument2> spDoc;
LRESULT lRes;
UINT nMsg = ::RegisterWindowMessage(_T("WM_HTML_GETOBJECT"));
::SendMessageTimeout(hWndChild, nMsg, 0L, 0L, SMTO_ABORTIFHUNG, 1000, (DWORD*)&lRes);
LPFNOBJECTFROMLRESULT pfObjectFromLresult = (LPFNOBJECTFROMLRESULT)::GetProcAddress(hInst, _T("ObjectFromLresult"));
if (pfObjectFromLresult != NULL)
{
HRESULT hr = (*pfObjectFromLresult )(lRes, IID_IHTMLDocument2, 0, (void**)&spDoc);
if (SUCCEEDED(hr))
{
IHTMLElement *p = NULL;
spDoc->get_body(&p); //接下去就跟操作IE一样
}
}
}
::FreeLibrary(hInst);
}
::CoUninitialize();
}