Executing MS-DOS commands

Hi,
    I was thinking of creating my own smaller version of Winzip, but am unsure how I would go about coding it so that the Onclick event of a button would execute the following MS-DOS command (for example):

c:\test\pkzip c:\a *.*

Cheers in advance,
bmarfellAsked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

mhervaisCommented:
why not having a look at the shellexecute (or shellexuteex) method?

regards, Marc
0
rwilson032697Commented:
Hi bmarfell,

Here is some code written by PhilipLeighs from my PAQs which should do the trick for you:

Call LaunchConsoleAndWait with two empty string lists from your click event. When the function returns one string list contains everything that was written to stdout, and the other contains anything written to stderr.
Note that you don't actually see the console window.

Paste the entire code into a unit called ConsolePipe.pas.

Cheers,

Raymond.


unit ConsolePipe;

interface

uses Windows, Classes, SysUtils;

procedure LaunchConsoleAndWait(ExeName: string; Args: string; WorkingDir: string; Output: TStringList; Errors: TStringList);

implementation

procedure LaunchConsoleAndWait(ExeName: string; Args: string; WorkingDir: string; Output: TStringList; Errors: TStringList);
  var sa: TSECURITYATTRIBUTES;
      si: TSTARTUPINFO;
      pi: TPROCESSINFORMATION;
      hPipeOutputRead: THANDLE;
      hPipeOutputWrite: THANDLE;
      hPipeErrorsRead: THANDLE;
      hPipeErrorsWrite: THANDLE;

      Res: Boolean;
      env: array [0..100] of Char;
      pWorkingDir: PChar;

      bTest: Boolean;
      dwNumberOfBytesRead: DWORD;
      szBuffer: array [0..256] of Char;
      Stream: TMemoryStream;

      CRCRLFPos: Integer;
  begin
    sa.nLength := sizeof(sa);
    sa.bInheritHandle := true;
    sa.lpSecurityDescriptor := nil;

    CreatePipe(hPipeOutputRead,
               hPipeOutputWrite,
               @sa,
               0);
    CreatePipe(hPipeErrorsRead,
               hPipeErrorsWrite,
               @sa,
               0);

    ZeroMemory(@env, SizeOf(env));
    ZeroMemory(@si, SizeOf(si));
    ZeroMemory(@pi, SizeOf(pi));
    si.cb := SizeOf(si);
    si.dwFlags := STARTF_USESHOWWINDOW or STARTF_USESTDHANDLES;
    si.wShowWindow := SW_HIDE;
    si.hStdInput   := 0;
    si.hStdOutput  := hPipeOutputWrite;
    si.hStdError   := hPipeErrorsWrite;
    pWorkingDir := nil;
    if WorkingDir <> '' then
      pWorkingDir := PChar(WorkingDir);

    if ExeName <> '' then
      Res := CreateProcess(
          PChar(ExeName),
          PChar(' ' + Args),
          nil,
          nil,
          true,
          CREATE_NEW_CONSOLE or NORMAL_PRIORITY_CLASS,
          @env,
          pWorkingDir,
          si,
          pi)
    else
      Res := CreateProcess(
          nil,
          PChar(Args),
          nil,
          nil,
          true,
          CREATE_NEW_CONSOLE or NORMAL_PRIORITY_CLASS,
          @env,
          pWorkingDir,
          si,
          pi);
    if not Res then
      begin
        CloseHandle (hPipeOutputRead);
        CloseHandle(hPipeOutputWrite);
        CloseHandle (hPipeErrorsRead);
        CloseHandle(hPipeErrorsWrite);
        raise Exception.Create('Unable to execute ' + ExeName);
        exit;
      end;

    CloseHandle(hPipeOutputWrite);
    CloseHandle(hPipeErrorsWrite);

    //Read output pipe
    Stream := TMemoryStream.Create;
    try
      while true do
        begin
          bTest:=ReadFile(
                hPipeOutputRead,
                szBuffer,
                256,
                dwNumberOfBytesRead,
                nil);
          if not bTest then
            begin
              break;
            end;
          CRCRLFPos := Pos(#13#10, szBuffer);
          while CRCRLFPos > 0 do
            begin
              szBuffer[CRCRLFPos - 1] := ' ';
              CRCRLFPos := Pos(#13#10, szBuffer);
            end;
          Stream.Write(szBuffer, dwNumberOfBytesRead);
        end;
      Stream.Position := 0;
      Output.LoadFromStream(Stream);
    finally
      Stream.Free;
    end;

    //Read error pipe
    Stream := TMemoryStream.Create;
    try
      while true do
        begin
          bTest:=ReadFile(
                hPipeErrorsRead,
                szBuffer,
                256,
                dwNumberOfBytesRead,
                nil);
          if not bTest then
            begin
              break;
            end;
          CRCRLFPos := Pos(#13#10, szBuffer);
          while CRCRLFPos > 0 do
            begin
              szBuffer[CRCRLFPos - 1] := ' ';
              CRCRLFPos := Pos(#13#10, szBuffer);
            end;
          Stream.Write(szBuffer, dwNumberOfBytesRead);
        end;
      Stream.Position := 0;
      Errors.LoadFromStream(Stream);
    finally
      Stream.Free;
    end;

    WaitForSingleObject (pi.hProcess, INFINITE);
    CloseHandle (pi.hThread);
    CloseHandle (pi.hProcess);
    CloseHandle (hPipeOutputRead);
    CloseHandle (hPipeErrorsRead);
  end;

end.
0

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
rwilson032697Commented:
Now, a problem with using WaitForSingleObject is that messages are not handled anymore. So you can call it in a thread like this:

If you want to get the console output you can merge the two...

Cheers,

Raymond.


unit runThread_;

interface

uses
  Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls,
  ExtCtrls, ComCtrls;

type
  TForm1 = class(TForm)
    Button1: TButton;
    procedure Button1Click(Sender: TObject);
  private
    { Private-Deklarationen}
  public
    { Public-Deklarationen}
  end;

var Form1 : TForm1 = nil;

implementation

{$R *.DFM}

const unitName = 'runThread_.';

type TRunThread = class(TThread)
  private
    processHandle : cardinal;
    processReady  : boolean;
    waitingThread : cardinal;
    procedure Execute; override;
  end;

procedure TRunThread.Execute;
begin
  WaitForSingleObject(processHandle,INFINITE);   // This call does not return, unless copy is stopped
  processReady:=true;                            // Set "processReady" flag for main thread
  PostThreadMessage(waitingThread,WM_NULL,0,0);  // Wake up main thread
                                                 // If you call Application.HandleMessage (see below) in the
                                                 // main thread, the main thread is sleeping the most time in
                                                 // winAPI "waitMessage". So we send a "dummy" message in order
                                                 // to let the main thread return from Application.HandleMessage
end;

procedure TForm1.Button1Click(Sender: TObject);
var si  : TStartupInfo;
    pi  : TProcessInformation;
    dw1 : dword;
begin
  enabled:=false;
  caption:='start copy...';
  ZeroMemory(@si,sizeOf(si)); si.cb:=sizeOf(si);
  si.dwFlags:=STARTF_USESHOWWINDOW; si.wShowWindow:=SW_HIDE;
  if CreateProcess(nil,'c:\command.com /c copy c:\autoexec.bat c:\test.bat >c:\output.txt',nil,nil,false,0,nil,nil,si,pi) then begin
    caption:='copy started...';
    with TRunThread.Create(true) do         // create the thread object, but do not start it now...
      try
        processHandle:=pi.hProcess;         // tell the thread what process it has to watch
        processReady:=false;                // flag for the loop (see below)
        waitingThread:=GetCurrentThreadID;  // the current threadID for the wakeup message (see above)
        caption:='wait for copy...';
        Resume;                             // now all information is prepared; so let's start the thread
        repeat
          Application.HandleMessage;        // message loop
        until Application.Terminated or processReady;  // continue with normal program when either the
                                                       // started process has stopped or our program is closed
        caption:='copy stopped...';
      finally Free end;
    GetExitCodeProcess(pi.hProcess,dw1);
    CloseHandle(pi.hThread); CloseHandle(pi.hProcess); // Never forget to close handles...
    caption:='ready... (exitCode='+IntToStr(dw1)+')';
  end else caption:='could not start copy...';
  enabled:=true;
end;

end.


0
Introducing Cloud Class® training courses

Tech changes fast. You can learn faster. That’s why we’re bringing professional training courses to Experts Exchange. With a subscription, you can access all the Cloud Class® courses to expand your education, prep for certifications, and get top-notch instructions.

bmarfellAuthor Commented:
RWilson,
  Wow! I got an A+ in the 2nd year Delphi paper I did at University, but you have me pretty much dazzled with the above stuff. I hadn't even heard of the TSECURITYATTRIBUTES, TSTARTUPINFO, TPROCESSINFORMATION, and THANDLE class types before. Are these part of the Windows API?

Are there any resources on the Web that you know of concerning the Windows API?

Cheers in advance,
0
rwilson032697Commented:
Not so sure about the web, but there are a bunch of books (look here: http://www.wargaming.net/Programming/110/Win32_API_index.htm)

There are a lot of bits and pieces on the net, use the likes of AltaVista.com to find them:

eg: http://www.efg2.com/lab/library/Delphi/Graphics/Win32API.htm

http://pandonia.canberra.edu.au/ssw/processes/win32.html

The Win32 help in Delphi is fairly extensive too...

Cheers,

Raymond.
0
bmarfellAuthor Commented:
Thanks for all your help.
0
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
Delphi

From novice to tech pro — start learning today.