MFC中CHtmlView和JS的相互调用

来源:互联网 发布:零基础学java第3版pdf 编辑:程序博客网 时间:2024/05/17 04:52

没废话,直接上步骤:


1、创建一个继承自CHtmlView的类;
2、构造函数中添加

CNewHtmlView::CNewHtmlView(){// 允许自动化EnableAutomation();}

3、重载 virtual HRESULT OnGetExternal( LPDISPATCH *lppDispatch); 

HRESULT CNewHtmlView::OnGetExternal( LPDISPATCH *lppDispatch ){// 返回自身的IDispatch接口*lppDispatch = GetIDispatch(TRUE);return S_OK;}

// JS调用C++部分
4、头文件中添加宏

DECLARE_DISPATCH_MAP

类似DECLARE_MESSAGE_MAP,具体自己Google
5、.cpp中添加接口映射

// 添加供JS调用的函数BEGIN_DISPATCH_MAP(CNewHtmlView, CHtmlView)DISP_FUNCTION(CNewHtmlView, "CB_FunctionInsallApp", CB_FunctionInsallApp, VT_EMPTY, VTS_DISPATCH)DISP_FUNCTION(CNewHtmlView, "CB_FunctionTryPlay", CB_FunctionTryPlay, VT_EMPTY, VTS_DISPATCH)END_DISPATCH_MAP()// 实现void CNewHtmlView::CB_FunctionInsallApp(IDispatch *pDispVal){CComDispatchDriver spData = pDispVal;CComVariant varProperty;spData.GetPropertyByName(L"PropertyName",&varProperty)}

说明:DISP_FUNCTION(CNewHtmlView, "JS中调用的函数名", C++中对应的函数名称, 返回值, 参数[多个参数以空格隔开,VTS_DISPATCH一般作为结构体参数])
获取结构体内容
6、调用js函数

HRESULT CNewHtmlView::OnInvokeJS( WPARAM wParam, LPARAM lParam ){// 组织参数CArray<CComVariant, CComVariant &> _param;_param.Add( CComVariant("123" ));_param.Add( CComVariant( "456"));CComQIPtr<IHTMLDocument2> _document;m_pBrowserApp->get_Document( (IDispatch **)&_document );CComDispatchDriver _script;_document->get_Script(&_script);_script.InvokeN("js中函数名称", &_param[0], param.GetCount());return S_OK;}

搞定,收工~!

0 0