본문 바로가기
Delphi Tip/+Tip

프로그램에서 DOS 명령어 처리

by MonoSoft 2023. 12. 29.
728x90
반응형

프로그램에서  DOS 명령어 처리

 

728x90

 

 

 

 

 

 

1. 콘솔창(DOS창) 창 안띄우기
2. 끝날때까지 기다리기(실행이 끝난것을 감지하기)
3. 출력되는 내용을 화일로 저장하기

 

 

procedure TForm1.Button1Click(Sender: TObject);

var

  msg: string;

begin

// 1.Dos 명령 일괄처리 파일에서 명령어를 불러오고(<), 다시 파일로 저장(>)

if not RunDosCmd('cmd c:\out.txt', Msg, true) then

ShowMessage(msg) else ShowMsg(Msg);

// 2.현재 도스 명령어를 실행하고, 결과를 파일로 저장('C/\out.txt)

if not RunDosCmd('Dir/w >c:\out.txt', Msg, true) then

ShowMessage(msg) else ShowMsg(Msg);

// 3.Rename 실행 임의 Directory의 파일을 같은 directory 다른 이름으로

if not RunDosCmd('rename C:MRX_NT\text.txt text1.txt', Msg, true) then

ShowMessage(msg) else ShowMsg(Msg);

end;

 

function RunDosCmd(cmd: string; var Msg: string; bNT: boolean): boolean;

var

pInfo : PROCESS_INFORMATION; sInfo : STARTUPINFO;

exitCode: DWORD;

s : string;

begin

result := false;

sInfo.cb := sizeof(STARTUPINFO);

sInfo.lpReserved := nil;

sInfo.lpReserved2 := nil;

sInfo.cbReserved2 := 0;

sInfo.lpDesktop := nil;

sInfo.lpTitle := nil;

sInfo.dwFlags := STARTF_USESHOWWINDOW + STARTF_USESTDHANDLES;

sInfo.dwX := 0;

sInfo.dwY := 0;

sInfo.dwFillAttribute := 0;

sInfo.wShowWindow := SW_HIDE;

if not bNT then

s := 'command.exe /c ' else s := 'cmd.exe /c ';

if not CreateProcess(nil, PChar(s + cmd), //c:\MRX_NT\rmxnt.exe c:\out.txt nil, nil, TRUE, 0, nil, 'c:\', sInfo, pInfo) then begin

Msg := 'ERROR: Cannot launch child process';

exit;

end;

 

// Give the process time to execute and finish WaitForSingleObject(pInfo.hProcess, INFINITE);

if (GetExitCodeProcess(pInfo.hProcess, exitCode)) then

case exitCode of

STILL_ACTIVE: msg := 'Process is still active';

else begin msg := 'OK';

result := true;

end;

end

else

msg := 'GetExitCodeProcess() failed';

end;

728x90
반응형

댓글