A while ago, I posted [WayBack] 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 [WayBack] TCommandParser class that does commandline parsing for you. Since it has [WayBack] virtually no documentation, here are a few things to get started. It works even in Delphi 2007.
I have a HiddenExecutable example at our open source bo repository.
Basically you:
- 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 [WayBack] AddSwitch calls to setup the parameters with both abbreviated and full commandline switches (like
h and help)
- 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:
- TCommandParser has a
HelpText method that fully automatically assembles a helptext based upon what you fed it with the AddSwitch methods.
- 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 Embarcadero [WayBack] radstudiodemos.sourceforge.net demo repository:
CommandParser in '...\radstudiodemos.sourceforge.net\branches\RadStudio_XE2\Delphi\Database\dbExpress\Utils\CommandParser.pas',
PropertyHelpers in '...\radstudiodemos.sourceforge.net\branches\RadStudio_XE2\Delphi\Database\dbExpress\DbxDataPump\PropertyHelpers.pas',
ParseIds in '...\radstudiodemos.sourceforge.net\branches\RadStudio_XE2\Delphi\Database\dbExpress\DbxDataPump\ParseIds.pas',
Edit: [WayBack] John Kaster wrote a nice [WayBack] article on EDN that includes [WayBack] more details on using the TCommandParser.
Note the above mentioned code mostly is on [WayBack] https://bitbucket.org/jeroenp/wiert.me/src/tip/Native/Delphi/Apps/Console/HiddenExecuteConsoleProject
Since Delphi XE7, this unit does not ship with Delphi any more, but it is still at [WayBack] RAD Studio Demo Code / Code / [r2029] /branches/RadStudio_XE6/Object Pascal/Database/dbExpress/Utils/CommandParser.pas.
–jeroen
via: [WayBack] delphi – Suggestions for how to define command line parameters – Stack Overflow.