我需要在VB6上确定当前dll/ocx运行时的路径。 不能使用app.path
,因为它返回使用 dll 的exe
的路径。
基于此答案getThisDLLPath()
返回当前 dll/ocx 的完全限定名
GetModuleHandleExA
获取加载的 dll 中公共函数的句柄。
GetModuleFileNameW
获取句柄的完整路径
getThisDLLPath()
也被用作GetModuleHandleExA
的目标内存地址,所以它需要公开并在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