从delphi显示目录

use*_*405 0 windows delphi cmd shellexecute

我想使用Delphi(7)的DOS命令显示目录的内容.使用Win10 - 64

以下程序显示DOS shell但不显示目录内容.我的代码出了什么问题?

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.
Run Code Online (Sandbox Code Playgroud)

Ken*_*ite 5

在Windows 10上运行代码返回2,即ERROR_FILE_NOT_FOUND.

我在32位和64位目标平台上通过将其更改为:

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;
Run Code Online (Sandbox Code Playgroud)

/k说运行的一个新实例cmd.exe,并保持窗口打开.有关更多详细信息,请cmd /?从命令提示符运行.

请注意,错误处理ShellExecute非常有限.如果您希望全面检查错误,则必须使用ShellExecuteEx.

  • 请注意,`ShellExecute()`返回的许多错误代码不是标准的Win32错误代码.在这种特殊情况下,发生`ShellExecute()`的错误2确实意味着"找不到文件".如果你需要依赖单独的错误代码,最好使用`ShellExecuteEx()`,因为它使用`GetLastError()`来报告它的错误代码. (4认同)