解决 DELPHI 中执行外部命令出现屏幕一闪的问题的方法

发布时间 2024-01-13 21:15:52作者: 月如无恨月常圆

解决 DELPHI 中执行外部命令出现屏幕一闪的问题的方法

有的时候我们在DELPHI中使用ShellExecuteEx(exInfo: TShellExecuteInfo)函数执行一些外部命令,但会出现,屏幕一闪的问题,解决方法如下:
设置 exinfo.nShow := SW_HIDE; //隐藏命令执行的窗口,不会出现屏幕一闪的情况
在exinfo.nShow := SW_SHOWNORMAL 情况下,屏幕会出现一闪的情况。
举个例子说明(例子不一定恰当,只是为了说明):将某个文件夹下的某一类文件通过外部命令统计数量,将该数量存在在一个文本文件里,然后读出来显示。

unit Unit2;

interface

uses
  Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
  Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, Vcl.Buttons,ShellAPI,
  Vcl.ExtCtrls;

type
  TForm2 = class(TForm)
    BitBtn1: TBitBtn;
    Label1: TLabel;
    procedure BitBtn1Click(Sender: TObject);
  private
    { Private declarations }
  public
    { Public declarations }
  end;

var
  Form2: TForm2;

implementation

{$R *.dfm}

function ShellExecute_AndWait(FileName: string; Params: string): Boolean;
var
  exInfo: TShellExecuteInfo;
  Ph: DWORD;
begin
  FillChar(exInfo, SizeOf(exInfo), 0);
  with exInfo do
  begin
    cbSize := SizeOf(exInfo);
    fMask := SEE_MASK_NOCLOSEPROCESS or SEE_MASK_FLAG_DDEWAIT;
    Wnd := GetActiveWindow();
    exInfo.lpVerb := 'open';
    exInfo.lpParameters := PChar(Params);
    lpFile := PChar(FileName);
    //nShow := SW_SHOWNORMAL;      //这个会出现屏幕一闪的情况
    nShow := SW_HIDE;              //隐藏命令执行的窗口,不会出现屏幕一闪的情况
  end;
  if ShellExecuteEx(@exInfo) then
    Ph := exInfo.hProcess
  else
  begin
    ShowMessage(SysErrorMessage(GetLastError));
    Result := true;
    exit;
  end;
  while WaitForSingleObject(exInfo.hProcess, 50) <> WAIT_OBJECT_0 do
    Application.ProcessMessages;
  CloseHandle(Ph);

  Result := true;
end;


procedure TForm2.BitBtn1Click(Sender: TObject);
Var
  F1 : TextFile;
  FileCounts:string;
begin
  if ShellExecute_AndWait('cmd.exe','/c dir E:\GITEE_HT\XTCSH\*.PAS /b /a-d| find /v /c "&#@" > FileCounts.txt') then
  begin
      AssignFile(F1,'FileCounts.txt');
      Reset(F1);
      Readln(F1,FileCounts);
      Label1.Caption := '文件数量是:'+FileCounts;
      CloseFile(F1);
  end;
end;

end.