VBS调用ATL编写的COM组件

时间:2020-12-19 23:16:22

参考文章:http://blog.csdn.net/collin1211/article/details/1864624

不使用连接点,而是使用属性来处理事件回调。

IDL文件

import "oaidl.idl";
import "ocidl.idl";

[
object,
uuid(7E153966-BF67-4F02-BE64-80CB780A2EEF),
dual,
nonextensible,
helpstring("IComVBSDllExample Interface"),
pointer_default(unique)
]
interface IComVBSDllExample : IDispatch{
[id(1), helpstring("method Method1")] HRESULT Method1(void);
[propget, id(2), helpstring("property OnEvent1")] HRESULT OnEvent1([out, retval] IDispatch** pVal);
[propput, id(2), helpstring("property OnEvent1")] HRESULT OnEvent1([in] IDispatch* newVal);
};
[
uuid(08476D23-AECC-4CFF-9473-9C388E6AB86A),
version(1.0),
helpstring("ComVBSDll 1.0 Type Library")
]
library ComVBSDllLib
{
importlib("stdole2.tlb");
[
uuid(F44D811E-74ED-472A-8BAB-8FFC8AB07BE4),
helpstring("ComVBSDllExample Class")
]
coclass ComVBSDllExample
{
[default] interface IComVBSDllExample;
};
};

部分实现代码

STDMETHODIMP CComVBSDllExample::Method1(void)
{
// TODO: Add your implementation code here
OnEvent1(20);
return S_OK;
}
STDMETHODIMP CComVBSDllExample::get_OnEvent1(IDispatch** pVal)
{
// TODO: Add your implementation code here
*pVal = m_onEvent1;
return S_OK;
}

STDMETHODIMP CComVBSDllExample::put_OnEvent1(IDispatch* newVal)
{
// TODO: Add your implementation code here
m_onEvent1 = newVal;
return S_OK;
}

int CComVBSDllExample::OnEvent1(int arg1)
{
if (m_onEvent1) {
_variant_t vaResult;
_variant_t vaArg1(arg1);
DISPPARAMS disParams = {&vaArg1, NULL, 1, 0};
m_onEvent1->Invoke(0, IID_NULL, LOCALE_USER_DEFAULT, DISPATCH_METHOD, &disParams, &vaResult, NULL, NULL);
return (int)vaResult;
}
return 0;
}

VBS调用代码

dim comDll
set comDll = CreateObject("ComVBSDll.ComVBSDllExample")
comDll.OnEvent1 = GetRef("ComDll_Event1")
comDll.Method1()

Sub ComDll_Event1(ByVal arg1)
WScript.Echo(arg1)
end Sub