Find out whether Word was launched from its shortcut or by double-clicking a file

Article contributed by Will Rickards and Dave Rado

Option Explicit

Public Declare Function GetCommandLine Lib "kernel32" _
         Alias "GetCommandLineA" () As Long

Public Declare Function lstrcpy Lib "kernel32" _
        Alias "lstrcpyA" (ByVal lpString1 As String, ByVal lpString2 As Long) As Long

Public Declare Function lstrlen Lib "kernel32" _
        Alias "lstrlenA" (ByVal lpString As Long) As Long

Public Sub AutoExec()

Dim strCommandLine As String

'get the command line using CmdLinetoString function and GetCommandLine API call
strCommandLine = CmdLinetoString(GetCommandLine())

If Len(strCommandLine) <= Len(Chr(34) & Application.Path & "\" & _
        "winword.exe" & Chr(34) & " ") Then
    Msgbox " Word was launched from its shortcut"
    Msgbox " Word was launched by opening a file"
End If

End Sub

Public Function CmdLinetoString(ByVal lngPtr As Long) As String
    Dim strReturn As String
    Dim StringLength As Long
    'get the length of the string (not including the terminating null character)
    StringLength = lstrlen(lngPtr)
    'initialize our string so it has enough characters including the null character
    strReturn = String$(StringLength + 1, 0)
    'copy the string we have a pointer to into our new string
    lstrcpy strReturn, lngPtr
    'now strip off the null character at the end
    strReturn = Left$(strReturn, StringLength)
    'return the string
    CmdLinetoString = strReturn
End Function

Click to view Terms of Use page

Click to view Disclaimer page