Skip to content

Instantly share code, notes, and snippets.

@jeff123wang
Last active April 28, 2022 14:29
Show Gist options
  • Save jeff123wang/574c6abe71d7d52c199a87b843c76a3d to your computer and use it in GitHub Desktop.
Save jeff123wang/574c6abe71d7d52c199a87b843c76a3d to your computer and use it in GitHub Desktop.
When a function in the DLL is called, the DLL is loaded in memory. At that moment the DLL is "in use" and cannot be deleted or replaced. So maintenance is not possible when people are using the template.
'https://www.tek-tips.com/viewthread.cfm?qid=690668
Option Explicit
Private Declare Function GetModuleHandle Lib "kernel32" Alias "GetModuleHandleA" (ByVal lpModuleName As String) As Long
Private Declare Function FreeLibrary Lib "kernel32" (ByVal hLibModule As Long) As Long
' example DLL call
Private Declare Function WNetGetUser Lib "mpr.dll" Alias "WNetGetUserA" (ByVal lpName As String, ByVal lpUserName As String, lpnLength As Long) As Long
Private Sub Command1_Click()
Dim hLib As Long
' These are for the example library call
Dim lpName As String
Dim lpUserName As String
Dim lpnLength As Long
WNetGetUser lpName, lpUserName, lpnLength
hLib = GetModuleHandle("mpr")
ForceUnloadable hLib
Beep
End Sub
Private Sub ForceUnloadable(ByVal hModule As Long)
Dim FreeResult As Long
FreeResult = 1
Do Until FreeResult = 0 ' OK, library reference count is 0, and library is therefore unloadable
FreeResult = FreeLibrary(hModule)
Loop
End Sub
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment