Search code examples
delphiparamstr

Suggestions for how to define command line parameters


In my Delphi application, I would like to add command line parameters to automatically set some parameters in the login screen.

Currently I have a login screen where the user sets some information (like Server, database, user, password, AuthenticationType, AUtoLogin, ...).

I use MRU to populate the fields. Anyway, in big organizations, there is the need to do not let the user choose any info. For this, the simplest thing I can do in my scenario is to use command line parameters.

My question is how do you suggest to choose the command line parameters? I mean, should I go for a "position" approach or for some "tag" approach, for example:

MyProject.exe -s:MYSERVER -d:DATABASE

or

MyProject.exe MYSERVER DATABASE

In the first case I need to loop across all parameters using ParamStr and "decode" what they are. If they start with "-s:" I know that what follows is the server name. The second is more quick and dirty but may be more effective.

How to manage parameters that contain a "space"? Is it possible to automatically intercept them with ParamStr or should I handle all manually? (I mean is there a way to automatically tell to ParamStr that a parameter is containing a space (like using curly brackets or something).

What is the best practice?


Solution

  • Should I go for a "position" approach or for some "tag" approach?

    Without doubt you should tag your command line arguments. Positional approaches don't allow sufficient flexibility to omit parameters. Tagging makes it easier for the user to understand the arguments, especially when returning to previously written code. The tags should be self-documenting.

    One common scenario when you would have untagged arguments is when you have a file name or a list of file names.

    How to manage parameters that contain a "space"?

    The Windows convention is that spaces are escaped by putting double-quotes around the argument. The ParamStr parsing will recognise these and parse the arguments accordingly. What you see in ParamStr(i) is the argument with the quotes removed.


    The RTL comes with a useful helper function to aid your command-line argument parsing: FindCmdLineSwitch.