描述:
CComPtr<IShellWindows> psw;
psw.CoCreateInstance(CLSID_ShellWindows);
if(psw)
{
CDWordArray arHWNDShellWindows;
CTypedPtrArray<CPtrArray,CComQIPtrIWebBrowser2*> arShellWindows;//
long lShellWindowCount=0;
psw->get_Count(&lShellWindowCount);
for(long i=0;i<lShellWindowCount;i++)
{
CComPtr<IDispatch> pdispShellWindow;
psw->Item(COleVariant(i),&pdispShellWindow);
CComQIPtr<IWebBrowser2> pIE(pdispShellWindow);
if(pIE)
{
CString strWindowClass=GetWindowClassName(pIE);
if(strWindowClass==_T("IEFrame"))
{
HWND hWndID=NULL;
pIE->get_HWND((long*)&hWndID);
arHWNDShellWindows.Add((DWORD)hWndID);
arShellWindows.Add(new CComQIPtrIWebBrowser2(pIE));
}
}
}
CString s;
s.Format(_T("%d"),arHWNDShellWindows.GetSize());
if(arHWNDShellWindows.GetSize()>0)//at least one shell window found
//, get the top one in z order
{
//the first top-level window in zorder
HWND hwndTest=::GetWindow((HWND)arHWNDShellWindows[0],GW_HWNDFIRST);
DWORD m_dwCookie;
while( hwndTest)
{
for(int i=0;i<arHWNDShellWindows.GetSize();i++)
{
if(hwndTest==(HWND)arHWNDShellWindows[i])
{
LPUNKNOWN pUnkSink = GetIDispatch(FALSE);
BOOL badv=AfxConnectionAdvise((LPUNKNOWN)*arShellWindows[i],DIID_DWebBrowserEvents2,this->GetInterface(&IID_IUnknown),TRUE,&m_dwCookie); //连接到IE事件.
CString s;
s.Format(_T("%s"),badv?_T("成功"):_T("失败"));
m_pParent->AddEventToList(s);
break;
}
}
hwndTest = ::GetWindow(hwndTest, GW_HWNDNEXT);
}
}
for(int i=0;i<arShellWindows.GetSize();i++)
{
delete arShellWindows[i];
}
}
程序能够监听IE事件,可是关闭一个IE时,程序就崩溃了,请问是不是缺了什么!
解决方案1:
恩,先试试看,判断句柄是否有效:
BOOL IsWindow(
HWND hWnd // handle to window
);
毕竟这个我野没尝试过;-)