2

I need to determine the path of the current dll / ocx at runtime on VB6. Can't use app.path because it returns the path of the exe that's using the dll.

xvan
  • 4,554
  • 1
  • 22
  • 37
  • Does this answer your question? [Get DLL path at runtime](https://stackoverflow.com/questions/6924195/get-dll-path-at-runtime) – jac Dec 27 '19 at 18:18
  • @jac , That answer is for C++. Used that one as a reference to craft this one for VB6. I even cited it on my answer. – xvan Dec 27 '19 at 19:02

1 Answers1

3

Based on this answer getThisDLLPath() returns the fully qualified name of the current dll/ocx

GetModuleHandleExA gets the handle of a public function in a loaded dll.

GetModuleFileNameW gets the fullpath of a handle

getThisDLLPath() is also used as a target memory address for GetModuleHandleExA, so it needs to be public and on a bas file.

Option Explicit
Private Declare Function GetModuleFileNameW Lib "kernel32.dll" _
    (ByVal hModule As Long, ByVal lpFilename As Long, ByVal nSize As Long) As Long
Private Declare Function GetModuleHandleExA Lib "kernel32.dll" _
    (ByVal dwFlags As Long, ByVal lpModuleName As Long, ByRef phModule As Long) As Boolean

Private Const GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS As Long = &H4
Private Const GET_MODULE_HANDLE_EX_FLAG_PIN As Long = &H1
Private Const GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT As Long = &H2

Private Function getThisDLLHandle() As Long
    Call GetModuleHandleExA(GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS Or _
             GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT, _ 
             AddressOf getThisDLLPath, getThisDLLHandle)
End Function

Public Function getThisDLLPath() As String
    Const MAX_PATH = 260&   
    Dim lphandle As Long        
    lphandle = getThisDLLHandle

    GetThisDLLPath = Space$(MAX_PATH - 1&)
    Call GetModuleFileNameW(lphandle, StrPtr(GetThisDLLPath), MAX_PATH)
End Function
xvan
  • 4,554
  • 1
  • 22
  • 37