• Welcome to PlanetSquires Forums.
 

RegFree COM in VB6

Started by David Maruca, April 03, 2010, 02:53:00 PM

Previous topic - Next topic

David Maruca

Hey guys,

I just want to share some of my findings with you all. I found a nice free utility called DirectCOM.dll located at http://www.thecommon.net/index.html which is written in PowerBasic that allows you to load com in VB6 without registering the component with a simple dll call. This is neat because now you can use PB to make com classes to use from MS Office apps without needing to install anything on the user's machine. Admin rights make simple macro distribution in an office crazy.

How to use it. Paste this code into a new module in VB6:

Option Explicit

'Used for dynamic loading of DirectCom.dll
Private Declare Function GetModuleHandle Lib "kernel32.dll" Alias "GetModuleHandleW" (ByVal DllName As Long) As Long
Private Declare Function LoadLibrary Lib "kernel32.dll" Alias "LoadLibraryW" (ByVal LibFilePath As Long) As Long

'******** Obj-Instantiation without using the registry *********
Declare Function GETINSTANCE Lib "DirectCom" (FName As String, ClassName As String) As Object  'CreateObject-Replacement (FileBased)
Declare Function GetInstanceEx Lib "DirectCom" (ByRef StrPtr_FilePath As Long, ByRef StrPtr_ClassName As Long, Optional ByVal UseAlteredSearchPath As Boolean = True) As Object
Declare Function GETINSTANCELASTERROR Lib "DirectCom" () As String 'if GETINSTANCE returns Nothing

Public Sub DirectComInit(AppPath As String)
    LoadDlls AppPath, "DirectCom.dll"
End Sub

'Access VBA replacement for App.Path
Public Function AppPath() As String
    Dim i As Long
    Do
      i = InStr(i + 1, CodeDb.Name, "\")
    Loop Until InStr(i + 1, CodeDb.Name, "\") = 0
    AppPath = Left(CodeDb.Name, i)
End Function

Private Sub LoadDlls(ByRef Path As String, ParamArray DllNames() As Variant)
    Dim Res As Long, DllName As String, i As Long
    For i = 0 To UBound(DllNames)
        DllName = DllNames(i)
        Res = GetModuleHandle(StrPtr(DllName))
        If Res = 0 Then Res = LoadLibrary(StrPtr(Path & DllName))
        If Res = 0 Then Err.Raise "Could not load library " & DllName
    Next i
End Sub


Then inside your code you can use GetInstance or GetInstanceEx in place of CreateObject. GetInstanceEx is newer and can handle unicode paths and probably more that I don't know about, but the paramaters must be string pointers.

Sub RegFreetest()
    'A small init routine to load DirectCOM.dll without it being in the system path
    'You can replace this routine if you wish...
    DirectComInit AppPath
   
    Dim obj As Object
   
    Set obj = GetInstanceEx(StrPtr(AppPath & "YourComDLL.dll"), StrPtr("ClassName"))

    Debug.Print obj.Method
End Sub


I hope this helps someone. They also have lots of other free useful stuff there like a very fast sqlite wrapper and some collection and dictionary classes.