CDHtmlDialog的基本使用(C++调用JS函数的实现)

来自:清泛网http://www.tsingfun.com/html/2015/dev_0826/CDHtmlDialog_cpp_call_js_interactive.html


CDHtmlDialog的基本使用(JS调用C++函数的实现)


本文基于以上文章,在其代码基础上拓展:
一、在主对话框上添加一个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;
}

最终运行效果如下:


工程代码点此下载

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值