[Webinar] Streamline your web hosting managementRegister Today

x
?
Solved

Executing MS-DOS commands

Posted on 2000-02-10
6
Medium Priority
?
176 Views
Last Modified: 2010-04-04
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,
0
Comment
Question by:bmarfell
  • 3
  • 2
6 Comments
 
LVL 4

Expert Comment

by:mhervais
ID: 2509272
why not having a look at the shellexecute (or shellexuteex) method?

regards, Marc
0
 
LVL 12

Accepted Solution

by:
rwilson032697 earned 800 total points
ID: 2509302
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
 
LVL 12

Expert Comment

by:rwilson032697
ID: 2509328
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
Receive 1:1 tech help

Solve your biggest tech problems alongside global tech experts with 1:1 help.

 

Author Comment

by:bmarfell
ID: 2510087
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
 
LVL 12

Expert Comment

by:rwilson032697
ID: 2510097
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
 

Author Comment

by:bmarfell
ID: 2510175
Thanks for all your help.
0

Featured Post

Free Tool: Subnet Calculator

The subnet calculator helps you design networks by taking an IP address and network mask and returning information such as network, broadcast address, and host range.

One of a set of tools we're offering as a way of saying thank you for being a part of the community.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Introduction I have seen many questions in this Delphi topic area where queries in threads are needed or suggested. I know bumped into a similar need. This article will address some of the concepts when dealing with a multithreaded delphi database…
Introduction Raise your hands if you were as upset with FireMonkey as I was when I discovered that there was no TListview.  I use TListView in almost all of my applications I've written, and I was not going to compromise by resorting to TStringGrid…
Enter Foreign and Special Characters Enter characters you can't find on a keyboard using its ASCII code ... and learn how to make a handy reference for yourself using Excel ~ Use these codes in any Windows application! ... whether it is a Micr…
How to fix display issue, screen flickering issue when I plug in power cord to the machine. Before I start explaining the solution lets check out once the issue how it looks like after I connect the power cord. most of you also have faced this…
Suggested Courses

590 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question