간혹 커맨드라인옵션에 값을 전달하고 싶을때가 있습니다.
예를들어
c>test.exe ID=haudgo Kor=80 Eng=90 Math=100
이런식으로요.
이렇게 막상 커맨드라인옵션에 값을 전달하려고 하니 델파이에서 기본적으로 제공하는 기능만으로는 전달된 값을 분석해 낼 수가 없네요.
그래서 하나 만들었습니다.
unit CmdLineParserU;
interface
uses
System.Classes, System.SysUtils;
type
TCmdLineParser = class(TObject)
private
FParams : TStringList;
protected
public
constructor Create; overload;
destructor Destroy; override;
property Params : TStringList read FParams;
function CmdLine : String;
function ParamStr(Index: Integer): String;
function ParamCount : Integer;
function FindParam(AParamStr: String) : Integer;
end;
implementation
constructor TCmdLineParser.Create;
var
I : Integer;
Param : String;
begin
FParams := TStringList.Create;
for I := 1 to ParamCount do
Begin
Param := Trim(System.ParamStr(i));
if Copy(Param, 1, 1) = '/' then Delete(Param, 1, 1);
if Copy(Param, 1, 1) = '-' then Delete(Param, 1, 1);
FParams.Add(Param);
End;
end;
destructor TCmdLineParser.Destroy;
begin
FreeAndNil(FParams);
end;
Function TCmdLineParser.CmdLine : String;
Begin
Result := System.CmdLine;
End;
Function TCmdLineParser.ParamStr(Index: Integer): String;
Begin
Result := System.ParamStr(Index);
End;
Function TCmdLineParser.ParamCount: Integer;
Begin
Result := System.ParamCount;
End;
Function TCmdLineParser.FindParam(AParamStr: String): Integer;
Begin
IF Params.Find(AParamStr, Result) Then Exit;
Result := Params.IndexOfName(AParamStr);
if Result > 1 then Exit;
Result := -1;
End;
end.
이렇게 유닛을 하나 만들어 놓고 아래와 같이 사용합니다.
procedure TForm1.Button1Click(Sender: TObject);
Var
i: Integer;
CmdLineParser : TCmdLineParser;
begin
CmdLineParser := TCmdLineParser.Create;
;커맨드라인옵션으로 전달된 모든 값들
for I := 0 to CmdLineParser.ParamCount - 1 do
Begin
Memo1.Lines.Add(CmdLineParser.Params.Names[i] + ' = ' + CmdLineParser.Params.ValueFromIndex[i]);
End;
;커맨드라인옵션으로 전달된 값 중 "Kor"의 값
Memo1.Lines.Add('Kor = ' + CmdLineParser.Value['Kor']);
;커맨드라인옵션으로 전달된 값 중 두번째 인수
Memo1.Lines.Add(CmdLineParser.ParamStr(2));
;커맨드라인옵션 중 "Kor"이 있는지 검사
IF CmdLineParser.FindParam('Kor') > -1 Then
Memo1.Lines.Add('Param "Kor" is Exist');
FreeAndNil(CmdLineParser);
end;
|