Solved

Passing Arguements to an VB.exe

Posted on 2002-04-01
6
270 Views
Last Modified: 2008-03-10
When I am calling an exe from my code, how do i pass arguements into an exe by using Shell(), if the exe is expecting arguements?  Is there some other way?

Thanks,
hxia
0
Comment
Question by:hxia
6 Comments
 
LVL 7

Accepted Solution

by:
Joe_Griffith earned 50 total points
ID: 6910902
l = Shell("program.exe arg1 arg2", vbNormalFocus)
0
 
LVL 4

Expert Comment

by:Steve Sirica
ID: 6910915
Shell() is ok but I found something even better.  Give this a whirl:

    Private Type STARTUPINFO
       cb               As Long
       lpReserved       As String
       lpDesktop        As String
       lpTitle          As String
       dwX              As Long
       dwY              As Long
       dwXSize          As Long
       dwYSize          As Long
       dwXCountChars    As Long
       dwYCountChars    As Long
       dwFillAttribute  As Long
       dwflags          As Long
       wShowWindow      As Integer
       cbReserved2      As Integer
       lpReserved2      As Long
       hStdInput        As Long
       hStdOutput       As Long
       hStdError        As Long
    End Type
   
    Private Type PROCESS_INFORMATION
       hProcess         As Long
       hThread          As Long
       dwProcessId      As Long
       dwThreadID       As Long
    End Type
   
    Private Declare Function WaitForSingleObject Lib "kernel32" (ByVal _
       hHandle As Long, ByVal dwMilliseconds As Long) As Long
   
    Private Declare Function CreateProcessA Lib "kernel32" (ByVal _
       lpApplicationName As String, ByVal lpCommandLine As String, ByVal _
       lpProcessAttributes As Long, ByVal lpThreadAttributes As Long, _
       ByVal bInheritHandles As Long, ByVal dwCreationFlags As Long, _
       ByVal lpEnvironment As Long, ByVal lpCurrentDirectory As String, _
       lpStartupInfo As STARTUPINFO, lpProcessInformation As _
       PROCESS_INFORMATION) As Long
   
    Private Declare Function CloseHandle Lib "kernel32" _
       (ByVal hObject As Long) As Long
   
    Private Declare Function GetExitCodeProcess Lib "kernel32" _
       (ByVal hProcess As Long, lpExitCode As Long) As Long
   
    Private Const NORMAL_PRIORITY_CLASS = &H20&
    Private Const INFINITE = -1&

Public Function ExecCmd(cmdline As String) As Long
    Dim proc     As PROCESS_INFORMATION
    Dim start    As STARTUPINFO
    Dim ret      As Long
   
    On Error GoTo Syntax_Error
   
    '* Initialize the STARTUPINFO structure:
    start.cb = Len(start)
   
    '* Start the shelled application:
    ret = CreateProcessA(vbNullString, cmdline, 0&, 0&, 1&, NORMAL_PRIORITY_CLASS, 0&, vbNullString, start, proc)

    '* Wait for the shelled application to finish:
    ret = WaitForSingleObject(proc.hProcess, INFINITE)
    Call GetExitCodeProcess(proc.hProcess, ret)
    Call CloseHandle(proc.hThread)
    Call CloseHandle(proc.hProcess)
    ExecCmd = ret

Exit_Sub:
    Exit Function
   
Syntax_Error:
    Call gsGenError
    Resume Exit_Sub
   
End Function

then just make the call kinda like this:
  dim lnReturn as long
  dim lsProg   as string
  lsProg = "abc.exe Parm2Pass"
  lnReturn = ExecCmd(lsProg)


What's nice about this is it will wait till execution of the called program completes to continue.  OF course you can get around that by tweaking the function.

Hope this is helpfull
Steve

0
 
LVL 44

Expert Comment

by:Arthur_Wood
ID: 6910993
to pass 'command line' arguments to a VB application, in the Application, use the Command$ function to retrieve the passes parameters, as a String, which you then parese as necessary.

Private Sub Form_Load()

dim strArgs as String

strArgs = Command$

' now parse strArgs to get the command-line parameters you passed in


End Sub

0
Does Powershell have you tied up in knots?

Managing Active Directory does not always have to be complicated.  If you are spending more time trying instead of doing, then it's time to look at something else. For nearly 20 years, AD admins around the world have used one tool for day-to-day AD management: Hyena. Discover why

 
LVL 5

Expert Comment

by:kcm76
ID: 6911518
u may use the command function.

The following example uses the Command function to get the command line arguments in a function that returns them in a Variant containing an array.

Function GetCommandLine(Optional MaxArgs)
   'Declare variables.
   Dim C, CmdLine, CmdLnLen, InArg, I, NumArgs
   'See if MaxArgs was provided.
   If IsMissing(MaxArgs) Then MaxArgs = 10
   'Make array of the correct size.
   ReDim ArgArray(MaxArgs)
   NumArgs = 0: InArg = False
   'Get command line arguments.
   CmdLine = Command()
   CmdLnLen = Len(CmdLine)
   'Go thru command line one character
   'at a time.
   For I = 1 To CmdLnLen
      C = Mid(CmdLine, I, 1)
      'Test for space or tab.
      If (C <> " " And C <> vbTab) Then
         'Neither space nor tab.
         'Test if already in argument.
         If Not InArg Then
         'New argument begins.
         'Test for too many arguments.
            If NumArgs = MaxArgs Then Exit For
            NumArgs = NumArgs + 1
            InArg = True
         End If
         'Concatenate character to current argument.
         ArgArray(NumArgs) = ArgArray(NumArgs) & C
      Else
         'Found a space or tab.
         'Set InArg flag to False.
         InArg = False
      End If
   Next I
   'Resize array just enough to hold arguments.
   ReDim Preserve ArgArray(NumArgs)
   'Return Array in Function name.
   GetCommandLine = ArgArray()
End Function

ALL THE BEST
KCM.
0
 
LVL 17

Expert Comment

by:inthedark
ID: 6912228
kcm76, the problem with you function is that it won't handle long file names example:

YourEXE.EXE "File name may have spaces.txt" ThisOneGotNone.txt


This one handles combined parameters, some with quotes and some without.  The is an example of usage at the start of the Function.



Public Function GetQuotedParameters(CmdLine As String) As Variant

' Returns parameters from a command line in the form of a variant string array

' example:

'Dim Params
'params = GetQuotedParameters(Command$)
'If params(0) = "$$ERROR$$" Then
'    MsgBox "Command Line Format Error Use /? to display command line options+vbcrlf+parsms(1)"
'    End
'ElseIf params(0) = "/?" Then
'    MsgBox "Command Line Options: /E for edit; /P for Print /PT for print to"
'    End
'End If


' This function handles parameters with/without quotes like:
' /THIS OR THAT
' "/THIS OR THAT" "AND THIS" OR THIS
' if not quoted assumes that space, tab or comma terminating

' returns element (0) = "$$ERROR$$" if an error see elsement (1) for message


Const QUOTE = """"
Const ONESPACE = " "

On Error GoTo BadNews

Dim w$ ' working copy of the command line provided

Dim nextchar As String
Dim ra As Variant ' Returned Array
Dim pc  As Long ' param count

Dim spos As Long ' position of first quote
Dim epos As Long ' position of last quote or next space
Dim paramlength  As Long
Dim complete As Boolean
Dim currentchar As String
Dim Param$

w$ = Trim$(CmdLine)                     ' make sure no leading spaces
w$ = Replace(w$, Chr$(9), Space$(1))    ' Remove Tabs
w$ = Replace(w$, ",", Space$(1))        ' Remove commas

pc = -1 ' param counter

' Handle no parameters
If Len(w$) = 0 Then
    GetQuotedParameters = Array(0)
    GetQuotedParameters(0) = ""
    Exit Function
End If

' Handle case where quotes aren't used
If InStr(w$, QUOTE) = 0 Then
    GetQuotedParameters = Split(w, ONESPACE)
    Exit Function
End If


' Find first/next characters
spos = 1
Do
   
    Do
   
        If spos > Len(w$) Then
            complete = True
            Exit Do
        End If
        currentchar = Mid(w$, spos, 1)
        If currentchar = ONESPACE Then
            spos = spos + 1 ' ignore spaces
            Exit Do
        ElseIf currentchar = QUOTE Then
            nextchar = QUOTE
            spos = spos + 1
        Else ' not quote or space must the the start of a parameter
            nextchar = ONESPACE
        End If
       
        If spos > Len(w$) Then
            complete = True
            Exit Do
        End If

        epos = InStr(spos, w$, nextchar)
        If epos = 0 Then
            epos = Len(w$) + 1
        End If
        paramlength = epos - spos
       
        If paramlength = 0 Then
            ' "" has been found
            Param$ = "": GoSub AddParam
        Else
            Param = Mid(w$, spos, paramlength)
            GoSub AddParam
        End If
        spos = epos + 1
        Exit Do
    Loop
    If complete Then Exit Do
Loop

If pc < 0 Then
    ReDim ra(0)
    ra(0) = ""
Else
    For pc = 0 To UBound(ra)
        ra(pc) = Trim$(ra(pc))
    Next pc
End If

GetQuotedParameters = ra

Exit Function

AddParam: ' store the parameter
    pc = pc + 1
    If pc = 0 Then
        ReDim ra(0)
    Else
        ReDim Preserve ra(pc)
    End If
    ra(pc) = Param
Return

BadNews:

pc = Err.Number
Param = Err.Description

On Error Resume Next ' reset error trap to stop potential loop

ReDim ra(1)
ra(0) = "$$ERROR$$"
ra(1) = "Error: " + CStr(pc) + " ~ " + Param

End Function

0
 

Author Comment

by:hxia
ID: 6913040
Thanks All!

hxia
0

Featured Post

Is Your AD Toolbox Looking More Like a Toybox?

Managing Active Directory can get complicated.  Often, the native tools for managing AD are just not up to the task.  The largest Active Directory installations in the world have relied on one tool to manage their day-to-day administration tasks: Hyena. Start your trial today.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

There are many ways to remove duplicate entries in an SQL or Access database. Most make you temporarily insert an ID field, make a temp table and copy data back and forth, and/or are slow. Here is an easy way in VB6 using ADO to remove duplicate row…
When trying to find the cause of a problem in VBA or VB6 it's often valuable to know what procedures were executed prior to the error. You can use the Call Stack for that but it is often inadequate because it may show procedures you aren't intereste…
As developers, we are not limited to the functions provided by the VBA language. In addition, we can call the functions that are part of the Windows operating system. These functions are part of the Windows API (Application Programming Interface). U…
Get people started with the process of using Access VBA to control Excel using automation, Microsoft Access can control other applications. An example is the ability to programmatically talk to Excel. Using automation, an Access application can laun…

832 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question