Autor Beitrag
Narses
ontopic starontopic starontopic starontopic starontopic starontopic starontopic starhalf ontopic star
Administrator
Beiträge: 10181
Erhaltene Danke: 1254

W10ent
TP3 .. D7pro .. D10.2CE
BeitragVerfasst: Mo 02.06.08 21:27 
Wie kann man einfach auf Kommandozeilenparameter zugreifen? Besonders z.B. über den Namen?

Vorschlag:
ausblenden volle Höhe Delphi-Quelltext
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:
15:
16:
17:
18:
19:
20:
21:
22:
23:
24:
25:
26:
27:
28:
29:
30:
31:
32:
33:
34:
35:
36:
37:
38:
39:
40:
41:
42:
43:
44:
45:
46:
type
  TForm1 = class(TForm)
    //...
  public
    ParamList: TStringList;
  end;

//...

procedure TForm1.FormCreate(Sender: TObject);
begin
  ParamList := TStringList.Create;
//ParamList.NameValueSeparator := ':'; // falls /param:value statt /param=value
  {$WARNINGS OFF}
  ParamList.CommaText := CmdLine; // Symbol 'CmdLine' ist plattformspezifisch
  {$WARNINGS ON}
  if (ParamList.Count > 0then begin
    Edit1.Text := ParamList.Strings[0]; // das hier ist Application.ExeName
    ParamList.Delete(0); // entfernen
  end;
  ListBox1.Items.Assign(ParamList);
  // so kann man einfach auf einen Kommandozeilenparamter über den Namen zugreifen
  if (UpperCase(ParamList.Values['/SWITCH']) = 'ON'then
    ShowMessage('Switch ist ON!');
end;

procedure TForm1.ListBox1Click(Sender: TObject);
  var
    i: Integer;
begin
  i := ListBox1.ItemIndex;
  if (i >= 0then begin
    // auf Kommandozeilenparamter über den Index zugreifen
    Edit2.Text := ParamList.Names[i];
    Edit3.Text := ParamList.ValueFromIndex[i];
  end
  else begin
    Edit2.Clear;
    Edit3.Clear;
  end;
end;

procedure TForm1.FormDestroy(Sender: TObject);
begin
  ParamList.Free;
end;
Beispiel für eine Kommandozeile:
ausblenden Quelltext
1:
test.exe /test=hallo "/welcome=hello world!" /switch=on					

Einzige "Unschönheit": wenn der Parameter-Wert Whitespaces oder Kommata enthält, muss der ganze Parameter in Anführungszeichen (siehe DOH zur Eigenschaft .CommaText), nicht nur der Wert.

Im Anhang das zugehörige Testprojekt.
_________________
There are 10 types of people - those who understand binary and those who don´t.
BenBE
ontopic starontopic starontopic starontopic starontopic starontopic starhalf ontopic starofftopic star
Beiträge: 8721
Erhaltene Danke: 191

Win95, Win98SE, Win2K, WinXP
D1S, D3S, D4S, D5E, D6E, D7E, D9PE, D10E, D12P, DXEP, L0.9\FPC2.0
BeitragVerfasst: Mo 02.06.08 23:53 
Alternativ kann man sich auch mit ParamStr und ParamCount die benötigten Parameter in die StringList packen. Hier sollte aber auf Grund der Vorgehensweise von ParamStr ein ähnliches Problem existieren.

_________________
Anyone who is capable of being elected president should on no account be allowed to do the job.
Ich code EdgeMonkey - In dubio pro Setting.