user1530405
user1530405

Reputation: 455

Display directory from delphi

I would like to display the contents of a directory using DOS commands from Delphi(7). Using Win10 - 64

The following program displays the DOS shell but does not display the directory contents. What is wrong with my code ?

unit Unit1;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls, shellapi;
type
  TForm1 = class(TForm)
    procedure FormCreate(Sender: TObject);
  private
    { Private declarations }
  public
    { Public declarations }
  end;
var
  Form1: TForm1;

  implementation

{$R *.dfm}

procedure TForm1.FormCreate(Sender: TObject);
var i : integer;
begin
   i := ShellExecute(Handle, nil, 'cmd.exe', PChar(' dir'), nil, SW_SHOW);
   caption := inttostr(i);
end;

end.

Upvotes: 0

Views: 769

Answers (1)

Ken White
Ken White

Reputation: 125749

Running your code on Windows 10 returns 2, which is ERROR_FILE_NOT_FOUND.

I got it to work, on both 32- and 64-bit target platforms, by changing it to this:

var
  ComSpec: string;
  retval: HINSTANCE;
begin
  ComSpec := GetEnvironmentVariable('comspec');
  retval := ShellExecute(Handle, nil, PChar(comspec), '/k dir', nil, SW_SHOW);
  if retval <= 32 then
    Caption := Format('Error, return value = %d', [retval])
  else
    Caption := 'Success';
end;

The /k says to run a new instance of cmd.exe and keep the window open. For more details, run cmd /? from a command prompt.

Note that the error handling of ShellExecute is very limited. If you wish to check for errors comprehensively then you must use ShellExecuteEx instead.

Upvotes: 5

Related Questions