Solved

Passing Arguements to an VB.exe

Posted on 2002-04-01
6
269 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
6 Surprising Benefits of Threat Intelligence

All sorts of threat intelligence is available on the web. Intelligence you can learn from, and use to anticipate and prepare for future attacks.

 
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

What Security Threats Are You Missing?

Enhance your security with threat intelligence from the web. Get trending threat insights on hackers, exploits, and suspicious IP addresses delivered to your inbox with our free Cyber Daily.

Join & Write a Comment

If you have ever used Microsoft Word then you know that it has a good spell checker and it may have occurred to you that the ability to check spelling might be a nice piece of functionality to add to certain applications of yours. Well the code that…
Most everyone who has done any programming in VB6 knows that you can do something in code like Debug.Print MyVar and that when the program runs from the IDE, the value of MyVar will be displayed in the Immediate Window. Less well known is Debug.Asse…
Get people started with the utilization of class modules. Class modules can be a powerful tool in Microsoft Access. They allow you to create self-contained objects that encapsulate functionality. They can easily hide the complexity of a process from…
This lesson covers basic error handling code in Microsoft Excel using VBA. This is the first lesson in a 3-part series that uses code to loop through an Excel spreadsheet in VBA and then fix errors, taking advantage of error handling code. This l…

760 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

Need Help in Real-Time?

Connect with top rated Experts

16 Experts available now in Live!

Get 1:1 Help Now