本文基于以上文章,在其代码基础上拓展:
一、在主对话框上添加一个C++按钮,步骤如下:
运行效果如下:
二、为C++按钮添加调用Js的代码:
JSCppInteractive.htm中添加一个js函数供C++调用,代码如下:
<script type="text/javascript">
function CppCallJsFunc() {
alert("JS alert弹出框!");
}
</script>
JSCppInteractiveDlg.h末尾添加如下代码:
HRESULT CallJSFunction(IHTMLDocument2* pDoc2,
CString strFunctionName,
DISPPARAMS dispParams,
VARIANT* varResult,
EXCEPINFO* exceptInfo,
UINT* nArgErr );
public:
afx_msg void OnBnClickedButton1();
JSCppInteractiveDlg.cpp末尾添加如下代码:
void CJSCppInteractiveDlg::OnBnClickedButton1()
{
// TODO: 在此添加控件通知处理程序代码
IHTMLDocument2* pDoc = NULL;
CDHtmlDialog::GetDHtmlDocument(&pDoc);
DISPPARAMS param = {0};
VARIANT vtRet;
CallJSFunction(pDoc, _T("CppCallJsFunc"), param, &vtRet, NULL, NULL);
}
HRESULT CJSCppInteractiveDlg::CallJSFunction(IHTMLDocument2* pDoc2,
CString strFunctionName,
DISPPARAMS dispParams,
VARIANT* varResult,
EXCEPINFO* exceptInfo,
UINT* nArgErr )
{
IDispatch *pDispScript = NULL;
HRESULT hResult;
hResult = pDoc2->get_Script(&pDispScript);
if(FAILED(hResult))
{
return S_FALSE;
}
DISPID dispid;
CComBSTR objbstrValue = strFunctionName;
BSTR bstrValue = objbstrValue.Copy();
OLECHAR *pszFunct = bstrValue ;
hResult = pDispScript->GetIDsOfNames(IID_NULL,
&pszFunct,
1,
LOCALE_SYSTEM_DEFAULT,
&dispid);
if (FAILED(hResult))
{
pDispScript->Release();
return hResult;
}
varResult->vt = VT_VARIANT;
hResult = pDispScript->Invoke(dispid,
IID_NULL, LOCALE_USER_DEFAULT,
DISPATCH_METHOD,
&dispParams,
varResult,
exceptInfo,
nArgErr);
pDispScript->Release();
return hResult;
}
最终运行效果如下:
工程代码点此下载。