目前我想自动化正在运行的 IE。我已使用以下代码成功附加了正在运行的 IE(我假设一个选项卡中只有一个 IE)
#include "atl/atlbase.h"
#include <exdisp.h>
#include <mshtml.h>
CComQIPtr<IWebBrowser2> pCurIE;
void __fastcall TForm4::Button3Click(TObject *Sender)
{
bool SuccessToHook = false;
CComPtr<IShellWindows> m_spSHWinds;
if (FAILED(m_spSHWinds.CoCreateInstance( __uuidof( ShellWindows)))){
return ;
}
LONG nCount;
m_spSHWinds->get_Count( &nCount);
ShowMessage(nCount);
for (int i = 0; i < nCount; i++) {
CComPtr<IDispatch> pDisp;
m_spSHWinds->Item( CComVariant(i), &pDisp);
CComQIPtr<IWebBrowser2> pIE(pDisp);
if (pIE == NULL){
continue ;
}
CComPtr<IDispatch> pDispDoc;
pIE->get_Document(&pDispDoc);
CComQIPtr<IHTMLDocument2> pHtmlDoc(pDispDoc);
if (pHtmlDoc){
pCurIE = pIE;
SuccessToHook = true;
break ;
}
}
ShowMessage(SuccessToHook ? "Success to hook." : "Failed to hook." );
}
现在我可以像导航和读取当前状态一样控制当前运行的 IE。但是因为我想在触发 onDocumentComplete Event 之类的事件时显示消息。我不知道如何按照我当前的代码监听事件。非常感谢带有 BCB 的简单示例代码,因为有一些带有 VC++ 的示例,但我的项目是在 C++ XE2 上的。
感谢@Remy Lebeau 和这个链接,我终于解决了我的问题。我把我的代码留在这里,希望它可能对其他人有帮助。
从 TEventDispatcher 派生的类
#include <exdisp.h>
#include <exdispid.h>
#include <mshtml.h>
#include <mshtmdid.h>
#include <utilcls.h>
//---------------------------------------------------------------------------
class TForm4;
class EventHandler:public TEventDispatcher<EventHandler,&DIID_DWebBrowserEvents2>{
private:
bool connected;
TForm4 *theform;
IUnknown* server;
protected:
HRESULT InvokeEvent(DISPID id, TVariant *params){
switch(id){
case DISPID_DOCUMENTCOMPLETE:
ShowMessage("On Document Complete");
break;
default:
break;
}
}
public:
EventHandler(){
connected = false; //not connected;
theform = false; //backptr to form is null
}
~EventHandler(){
if (connected)
Disconnect();
}
void Connect(TForm4 *form, IUnknown* srv){
server = srv;
theform = form; //back pointer to form to do stuff with it.
server->AddRef(); //addref the server
ConnectEvents(server);
}
void Disconnect(){
DisconnectEvents(server); //disconnect the events
server->Release();
}
};
开始听
void __fastcall TForm4::Button5Click(TObject *Sender)
{
Event = new EventHandler();
Event->Connect(this, pCurIE);
}
停止听
void __fastcall TForm4::Button6Click(TObject *Sender)
{
Event->Disconnect();
}