在 my answer to this question,提问者需要快速获取网络驱动器上文件夹的目录列表,我建议使用DOS“dir”命令.不幸的是,它是一个命令,而不是一个程序,所以你不能用CreateProcess执行它,所以我不
function Console(const Command: String): String; var StartupInfo: TStartupInfo; ProcessInfo: TProcessInformation; SecurityAttr: TSecurityAttributes; OutputPipeRead, OutputPipeWrite: THandle; Res: Boolean; BufSize: Cardinal; Buffer: String; BytesRead: Cardinal; begin FillChar(ProcessInfo, SizeOf(TProcessInformation), 0); FillChar(SecurityAttr, SizeOf(TSecurityAttributes), 0); SecurityAttr.nLength := SizeOf(SecurityAttr); SecurityAttr.bInheritHandle := true; SecurityAttr.lpSecurityDescriptor := nil; CreatePipe(OutputPipeRead, OutputPipeWrite, @SecurityAttr, 0); FillChar(StartupInfo, SizeOf(TStartupInfo), 0); StartupInfo.cb:=SizeOf(StartupInfo); StartupInfo.hStdInput := 0; StartupInfo.hStdOutput := OutputPipeWrite; StartupInfo.hStdError := OutputPipeWrite; StartupInfo.wShowWindow := SW_HIDE; StartupInfo.dwFlags := STARTF_USESHOWWINDOW or STARTF_USESTDHANDLES; Res := CreateProcess(nil, PChar(command), nil, nil, true, CREATE_DEFAULT_ERROR_MODE or CREATE_NEW_CONSOLE or NORMAL_PRIORITY_CLASS, nil, nil, StartupInfo, ProcessInfo); CloseHandle(OutputPipeWrite); Result := ''; if Res then begin SetLength(Buffer, 5000); BufSize := Length(Buffer); repeat Res := ReadFile(OutputPipeRead, Buffer[1], BufSize, BytesRead, nil); Result := Result + Copy(Buffer, 1, BytesRead); until not Res; WaitForSingleObject(ProcessInfo.hProcess, INFINITE); CloseHandle(ProcessInfo.hProcess); end; CloseHandle(OutputPipeRead); end;
样品用法:
ShowMessage(Console('cmd /c dir C:\'));