Author: William Gerbert
How do I make my program open a file specified as a command line parameter?
Answer:
To do this you need to use two functions - ParamCount and ParamStr. ParamCount
returns the number of command line parameters specified when the program was run.
ParamStr returns the parameter string of a specified parameter.
Basically all you need to do is check to see whether any parameters have been
passed, and if so evaluate them. The format of the parameter(s) is entirely up to
you, and you can produce code to deal with anything from a single parameter to a
whole range.
This simple example only allows for a single parameter - a file name - and if a
file name is passed the program loads that file when the form is shown. It requires
a single form with a Memo dropped onto it. Simply put the following code into the
form's OnShow event:
1 procedure TForm1.FormShow(Sender: TObject);
2 begin3 Memo1.Clear;
4 if ParamCount > 0 then5 begin6 case ParamCount of7 1: Memo1.Lines.LoadFromFile(Paramstr(1));
8 // allow for other possible parameter counts here9 else10 begin11 ShowMessage('Invalid Parameters');
12 Application.Terminate;
13 end;
14 end;
15 end;
To prove this code, after compiling the program of course, select Start | Run and
enter the following. Make sure that you replace the path of the exe file with the
correct path for your machine:
"F:\Borland\Delphi 3\Project1.exe" "c:\windows\win.ini"
This will open the Win.ini file in the memo in the application you created. Obviously this example could be extended considerably (there is no check to make sure that the file exists, for example) and the parameters could be parsed to determine what should be done with the information. It does not have to be a file opening command, it could just as easily be configuration information or indeed anything else that you may wish to specify when the program is run.