2015-05-13

A while ago, I posted the below StackOverflow answer.

Recently a friend asked me about command-line parsing in Delphi, so here is the re-run:

Delphi contains a really nice unit called CommandParser with a TCommandParser class that does commandline parsing for you.

Since it has virtually no documentation, here are a few things to get started.

I have a HiddenExecutable example at our open source bo repository.

Basically you:

setup a TComponent that contains the properties you want to expose as commandline parameters (that is THiddenExecuteSettings in the HiddenExecuteSettingsUnit

a commandline parser controller. In our case THiddenExecuteArguments in theTHiddenExecuteArgumentsUnit (in retrospect not such a good name) that contains an InitCommandLine method that sets up a TCommandParser instance passing it your TComponent

It then executes a couple of AddSwitch calls to setup the parameters with both abbreviated and full commandline switches (like h and help)

You can then call the ProcessCommandLine method on the TCommandParser instance to process the commandline and fill the properties of your TComponent (in my example, this is done in the ProcessCommandLine method).

Now comes the fun:

The TCommandParser has a HelpText method that fully automatically assembles a helptext based upon what you fed it with the AddSwitch methods.

The TCommandParser also has a SaveOptions method that allows you to save the current settings of your TComponent into a settings file.

The Delphi units you need are these which you can get from the Embarcaderoradstudiodemos.sourceforge.net demo repository:

Edit: John Kaster wrote a nice article on EDN that includes more details on using the TCommandParser.

–jeroen

via: delphi – Suggestions for how to define command line parameters – Stack Overflow.

Filed under: Delphi, Delphi 2007, Delphi 2009, Delphi 2010, Delphi XE, Delphi XE2, Delphi XE3, Delphi XE4, Delphi XE5, Delphi XE6, Delphi XE7, Development, Software Development

Show more