Monday, July 31, 2000

Programming Tips & Tricks #0008---Visual Basic Command Line Arguments

Programming Tips & Tricks #0008

Visual Basic Command Line Arguments

I recently received an email from a reader who wanted to know if its possible to run a Visual Basic executable program with command line arguments. The answer is yes, although this feature is not as robust as it is with executables compiled with other languages such as C.

What's a command line argument, you might ask?

Let me give you an example. Suppose you want to execute a program whose main form obtains its caption from an argument supplied by the user when the program is executed.

You can take advantage of Visual Basic's Command function, which returns a value equal to the argument supplied after the name of the Visual Basic executable. For instance, if the name of your executable is Test.exe, if you type this value into the Windows Start-Run dialog

Test.exe VB

and enter this code into the Load Event Procedure of the Startup Form

Private Sub Form_Load()

If Command <> "" Then
Form1.Caption = Command
End If

End Sub

when your form appears, "VB" will appear in the form's caption. Notice that we first check to see if the return value of the Command function is equal to an empty string, which will be the case if the user executes your program with no arguments.

Invariably, the next question that is asked is whether you can supply more than one argument to the executable. Other languages, such as C, populate multiple command line arguments separated by spaces into an argument array that is available to the program when it executes.

In Visual Basic, however, everything that appears after the name of the executable is considered a single string argument. Separating multiple arguments with commas, quotation marks, or other delimiters won't affect that--everything after the executable name is considered a single string argument and is returned as a single string from the Command Function.

For instance, typing this statement into the Start-Run Dialog Box

Test.exe I,love,VB

results in the form's caption being set to "I,love,VB".

However, with a little imagination and some string manipulation, it isn't difficult to come up with a workaround to this restriction.

No comments: