procedure TForm1.Button3Click(Sender: TObject);
begin 
 str1:='cmd.exe /c dir/b/a '+Combobox1.Text+'>c:\dir.txt'  ;
  winexec(pchar(str1),SW_HIDE);
  listbox1.Clear;
  listbox1.Items.LoadFromFile('c:\dir.txt');
end;为什么要单击按钮两下,列表框内的内容才能正确显示???

解决方案 »

  1.   

    因为winexec不等待cmd执行完就返回了
      

  2.   


    function WinExecAndWait32(FileName : PChar; CommandLine : PChar;
                              Visibility : Integer) : Integer;
     { returns -1 if the Exec failed, otherwise returns the process' exit
       code when the process terminates }
    var
      zAppName:array[0..512] of char;
      zCurDir:array[0..255] of char;
      WorkDir:ShortString;
      StartupInfo:TStartupInfo;
      ProcessInfo:TProcessInformation;
      Temp : DWORD;
    begin
      StrCopy(zAppName, FileName);
      StrCat(zAppName, CommandLine);
      GetDir(0, WorkDir);
      StrPCopy(zCurDir, WorkDir);
      FillChar(StartupInfo, Sizeof(StartupInfo),#0);
      StartupInfo.cb := Sizeof(StartupInfo);
      StartupInfo.dwFlags := STARTF_USESHOWWINDOW;
      StartupInfo.wShowWindow := Visibility;
      if not CreateProcess(nil,
          zAppName,                      { pointer to command line string }
          nil,                           { pointer to process security attributes }
          nil,                           { pointer to thread security attributes }
          false,                         { handle inheritance flag }
          CREATE_NEW_CONSOLE or          { creation flags }
          NORMAL_PRIORITY_CLASS,
          nil,                           { pointer to new environment block }
          nil,                           { pointer to current directory name }
          StartupInfo,                   { pointer to STARTUPINFO }
          ProcessInfo) then              { pointer to PROCESS_INF }
        Result := -1
      else begin
        WaitforSingleObject(ProcessInfo.hProcess,INFINITE);
        GetExitCodeProcess(ProcessInfo.hProcess,Temp);
        Result := Integer(Temp);                                      
      end;
    end;
    ///////////////
    WinExecAndWait32(pchar(str1),nil,SW_HIDE);