VB6:获取 DLL 的当前路径

VB6: Get current path of a DLL

我需要在 VB6 上运行时确定当前 dll/ocx 的路径。 不能使用 app.path 因为它 returns 使用 dll 的 exe 的路径。

基于this answergetThisDLLPath()returns当前的完全限定名dll/ocx

GetModuleHandleExA 获取加载的 dll 中 public 函数的句柄。

GetModuleFileNameW 获取句柄的完整路径

getThisDLLPath()也作为GetModuleHandleExA的目标内存地址,所以需要在public和一个bas文件上

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