Even more VB conversion fun!

| | Comments (0)

Except this time, it's useful for people of all ages! VB has an API called "Command", which gets you the command line arguments for your application. It gets them without the application name though -- just the stuff after the app name. REALbasic has something similar with the System.CommandLine API, except that gives you the entire command line, including the app name.

I can see uses for each way of doing things, but I can also see how people may find it hard to go from the RB way to the VB way.

So as a part of my VB Compatibility functions, I've ported the "Command" function into RB. It's really not as hard as you might think -- you just need to look for the first space character that's not inside of quotes. So another very simple parsing example demonstrates how do this:
[rbcode]
Protected Function Command() As String
// This should return just the command line part after the file
// name. It returns it without parsing it. In REALbasic, the
// command line comes with the filename, so we need to parse
// that out.

// Get the entire command line
dim commandLine as String = System.CommandLine

// Now parse the command line so that we can get just what
// is after the application name. We have to do this one
// character at a time, unfortunately
dim length as Integer = Len( commandLine )
dim ignoreSpaces as Boolean = false

for curPos as Integer = 1 to length
dim char as String = Mid( commandLine, curPos, 1 )

if char = """" then
// We found a quote, so we can ignore any spaces. If
// this is the second quote, then we can pay attention
// to spaces again.
ignoreSpaces = not ignoreSpaces
elseif not ignoreSpaces and (char = " " or char = Chr( 9 )) then
// We have a space. If we're ignoring spaces, then
// it doesn't matter. But if we're not, then we've found
// the end of the application name
return Trim( Mid( commandLine, curPos ) )
end if
next curPos

return ""
End Function[/rbcode]
Basically, every time we see a quote character, we know it's either time to start ignoring spaces, or start paying attention to spaces. If we find a space (or a tab) while paying attention to whitespace, we know that the remainder of the command line is comprised of the arguments.

So if you started an application from the command line like this: "My Application.exe" -r /c wahoo, then System.CommandLine will return it to you exactly like that, and the Command function will only return "-r /c wahoo".

Leave a comment

Disclaimer

I'm currently an employee of REAL Software. My blog is mine. The opinions represented in this blog are mine as well and may not represent my employer's opinions. All original material is copyrighted and property of the author.

REALbasic® is a registered trademark of REAL Software, Inc. REAL SQL Server™ and Lingua™ are pending trademarks of REAL Software, Inc. All rights reserved.