2005. február 10., csütörtök
Make my program open a file specified as a command line parameter?
Problem/Question/Abstract:
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:
procedure TForm1.FormShow(Sender: TObject);
begin
��Memo1.Clear;
��if ParamCount > 0 then
��begin
�� ��case ParamCount of
�� ����1: Memo1.Lines.LoadFromFile(Paramstr(1));
�� ����// allow for other possible parameter counts here
�� ��else
�� �����begin
�� �������ShowMessage('Invalid Parameters');
�� �������Application.Terminate;
�� �����end;
�� end;
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.
Feliratkozás:
Megjegyzések küldése (Atom)
Nincsenek megjegyzések:
Megjegyzés küldése