各位大侠:我用CHtmlView调用页面上的js函数,但是期望这个调用是在一个独立线程中实现的。因为如果是主线程实现,那么execScript无法返回的话(或者返回花很久时间)主线程都处于卡死等待状态,实在不能忍受。
主线程调用的实现:
BOOL CICServingAgentClientView::StatusNotify(string sType)
{
if(!m_pBrowserApp)
return FALSE;

CComQIPtr<IDispatch> pDocDisp ; 
HRESULT hr = m_pBrowserApp->get_Document(&pDocDisp);
if(FAILED(hr) || !pDocDisp)
return FALSE;

CComQIPtr <IHTMLDocument2> htmldoc;  
CComQIPtr <IHTMLFramesCollection2> htmlFrames;
hr = pDocDisp->QueryInterface(IID_IHTMLDocument2, (void**)&htmldoc);
if(FAILED(hr) && !htmldoc)
return FALSE;

CComQIPtr <IHTMLWindow2> htmlWin2;
hr = htmldoc->get_parentWindow(&htmlWin2);
if(SUCCEEDED(hr) && htmlWin2)
{
VARIANT var;

CComBSTR bsTemp = CString("if (typeof(StatusNotify) != \"undefined\") { StatusNotify('")  
+ CString(sType.c_str()) 
+ CString("'); }");

HRESULT hr1 = htmlWin2->execScript(bsTemp, 
//"{ StatusNotify(); }",
CComBSTR("javascript"), &var);
}

return TRUE;
}这套代码可以正常运行。CICServingAgentClientView派生于CHtmlView.
按照我期望的,我改成下面的代码:
static string g_sType = "";
UINT __cdecl MyScriptFunction( LPVOID pParam )
{
CICServingAgentClientView *pThis = (CICServingAgentClientView *)pParam;

CComQIPtr<IDispatch> pDocDisp ; 
HRESULT hr = pThis->m_pBrowserApp->get_Document(&pDocDisp);
if(FAILED(hr) || !pDocDisp)
return 1;

CComQIPtr <IHTMLDocument2> htmldoc;  
CComQIPtr <IHTMLFramesCollection2> htmlFrames;
hr = pDocDisp->QueryInterface(IID_IHTMLDocument2, (void**)&htmldoc);
if(FAILED(hr) && !htmldoc)
return 1;

CComQIPtr <IHTMLWindow2> htmlWin2;
hr = htmldoc->get_parentWindow(&htmlWin2);
if(SUCCEEDED(hr) && htmlWin2)
{
       VARIANT var;

               CComBSTR bsTemp = CString("if (typeof(StatusNotify) != \"undefined\") { StatusNotify('")  
        + CString(g_sType.c_str()) 
+ CString("'); }"); HRESULT hr = htmlWin2->execScript(bsTemp, 
//"{ StatusNotify(); }",
CComBSTR("JavaScript"), &var);

if (hr != S_OK)
return 1;
}

return 0;
}BOOL CICServingAgentClientView::StatusNotify(string sType)
{
if(!m_pBrowserApp)
return FALSE;

g_sType = sType;
CWinThread *pThread = AfxBeginThread(MyScriptFunction, this);
if (WaitForSingleObject(pThread->m_hThread, 500) == WAIT_TIMEOUT)
{
return FALSE;
}

return TRUE;
}
为了让MyScriptFunction能访问CICServingAgentClientView(CHtmlView)的保护成员m_pBrowserApp,我将其声明为CICServingAgentClientView的友员函数。但是这第二套代码无法正常调用到js函数。到此,我就不知道怎么回事了,请大侠们帮忙看看,谢谢赐教,感动无比~~