Who's your daddy or how to find the EXE that loaded the DLL

Applies To

OS:
VB:
NT, 9x, 2000
5, 6

Every now and then you need to find the name of the EXE that loaded you DLL component. The reasons for needing this information are diverse. For instance, I have a component that's used by both desktop and server-side web application. When I run a desktop application, I want to return text separated by vbCrLf. However, to HTML code vbCrLf means nothing. Web-application would prefer the text to be separated by <br>. I need to know where the component is running so that its output matches that of its container.

Thus the need for a procedure that returns the name of the EXE (or another DLL) that loaded the DLL component. I wish I could take credit for this code, but I can't. I posted the question on the newsgroups ages ago and some good soul answered. So here is the anonymous code. In your code simply call WhosYourDaddy function.

Add the following code to form, module or class
Option Explicit

'API Declarations
Private Declare Function GetModuleFileName Lib _
    "kernel32" Alias "GetModuleFileNameA" (ByVal _
    hModule As Long, ByVal lpFileName As String, _
    ByVal nSize As Long) As Long

Private Function WhosYourDaddy() As String
    Dim AppPath As String
    Const MAX_PATH = 260
    
    On Error Resume Next

    'allocate space for the string
    AppPath = Space$(MAX_PATH)
    
    If GetModuleFileName(0, AppPath, Len(AppPath)) Then
        'Remove NULLs from the result
        AppPath = Left$(AppPath, InStr(AppPath, vbNullChar) - 1)
        WhosYourDaddy = AppPath
    Else
        WhosYourDaddy = "Not Found"
    End If
End Function
End Code