Get the Command$ value from inside an ActiveX DLL

At times you may need to access the command line passed to the application from within an ActiveX DLL. Unfortunately, when inside a DLL the Command$ function returns a null string, so you have to resort to some API trickery:

Private Declare Function GetCommandLine Lib "kernel32" Alias "GetCommandLineA" _    () As LongPrivate Declare Function lstrcpy Lib "kernel32" Alias "lstrcpyA" (ByVal _    lpString1 As String, ByVal lpString2 As Long) As Long' inside the ActiveX DLL    Dim lpStr As Long, i As LongDim buffer As StringDim exePath As String, cmdLine As String    ' get a pointer to the command linelpStr = GetCommandLine()' copy into a local bufferbuffer = Space$(512)lstrcpy buffer, lpStr' extract the null-terminated stringbuffer = Left$(buffer, InStr(buffer & vbNullChar, vbNullChar) - 1)    If Left$(buffer, 1) = """" Then    ' if the string begins with double quotes,    ' find the closing quotes    i = InStr(2, buffer, """")    exePath = Mid$(buffer, 2, i - 2)    ' the rest of the line is the command line    cmdLine = LTrim$(Mid$(buffer, i + 1))Else    ' otherwise just find the space that separates    ' the EXE name/path and the command line    i = InStr(buffer, " ")    exePath = Left$(buffer, i - 1)    cmdLine = LTrim$(Mid$(buffer, i))End If

Now cmdLine holds the command line passed to the main application, and exePath is the name and path of the EXEcutable file. Note that according to MSDN exePath contains only the EXE name under NT/2000 (as opposed to the full path) but it doesn’t appear to be true (at least under NT SP4).

Share the Post:
Share on facebook
Share on twitter
Share on linkedin

Overview

Recent Articles: