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.
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