在VB中生成接口实例的方法很简单,对于没有UI的接口,直接声明或调用CreateObject函数就可以了。但有的时侯由于种种原因,知道接口的CLSID而不知接口的ProgID,甚至某些系统接口根本就没有ProgID,这时就要用到CoCreateInstance来生成接口实例了,具体代码如下:
'* ******************************************** * '* 模块名称:test.bas '* 功能:演示如何直接通过CLSID生成接口实例。 '* 作者:lyserver '* 联系方式:http://blog.csdn.net/lyserver '* ******************************************** * Option Explicit Private Type GUID data1 As Long data2 As Integer data3 As Integer data4(7) As Byte End Type Private Const S_OK As Long = &H0 Private Declare Function CoCreateInstance Lib "ole32.dll" (clsid As GUID,ByVal pUnkOuter As Long,ByVal dwClsContext As Long,riid As GUID,pvObj As Any) As Long Private Const CLSCTX_INPROC_SERVER As Long = &H1 Private Declare Function IIDFromString Lib "ole32.dll" (ByVal lpszIID As Long,iid As GUID) As Long Private Declare Function CLSIDFromString Lib "ole32" (ByVal lpszCLSID As Long,clsid As GUID) As Long Sub main() Dim shApp As Object Dim clsid As GUID,iid As GUID Const IID_IDispatch As String = "{00020400-0000-0000-C000-000000000046}" Const CLSID_IShell As String = "{13709620-C279-11CE-A49E-444553540000}" '以下三条语句用来创建Shell.Application接口实例, ' 相当于VB中Set shApp=CreateObject("Shell.Application")语句 If IIDFromString(StrPtr(IID_IDispatch),iid) <> S_OK Then Exit Sub If CLSIDFromString(StrPtr(CLSID_IShell),clsid) <> S_OK Then Exit Sub If CoCreateInstance(clsid,CLSCTX_INPROC_SERVER,iid,shApp) <> S_OK Then Exit Sub '用VB的方式调用接口的一个属性 MsgBox shApp.Windows.Count '释放接口 Set shApp = Nothing End Sub