Ветеран
Сообщения: 1133
Благодарности: 581
|
Профиль
|
Отправить PM
| Цитировать
R.M.L,
Примеры из Delphi World 6.0
Как запустить приложение и подождать пока оно отработает1
Код: 
{ **** UBPFD *********** by delphibase.endimus.com ****
>> Дождаться завершение внешнего приложения
Дожидается завершения внешнего процесса
Зависимости: shellAPI
Автор: elena_tark, elena_tark@freemail.ru, Калуга
Copyright: Собственное
Дата: 1 августа 2003 г.
***************************************************** }
procedure ShellExec(Sender: TObject);
var
ProcInfo: PShellExecuteInfo;
begin
(Sender as TControl).Enabled := False;
GetMem(ProcInfo, SizeOf(ProcInfo^));
with ProcInfo^ do
begin
Wnd := Handle;
cbSize := SizeOf(ProcInfo^);
lpFile := PChar('notepad.exe');
lpParameters := nil;
lpVerb := 'open';
nShow := SW_SHOW;
fMask := SEE_MASK_DOENVSUBST or SEE_MASK_NOCLOSEPROCESS;
end;
try
Win32check(ShellExecuteEx(ProcInfo));
while not Application.Terminated and
(WaitForSingleObject(ProcInfo.hProcess, 100) = WAIT_TIMEOUT) do
Application.ProcessMessages;
finally
if ProcInfo.hProcess <> 0 then
CloseHandle(ProcInfo.hProcess);
Dispose(ProcInfo);
(Sender as TControl).Enabled := True;
end;
end;
Как запустить приложение и подождать пока оно отработает2
Код: 
{ **** UBPFD *********** by delphibase.endimus.com ****
>> Запуск программы и ожидание ее завершения.
Функция запускает внешнюю программу, заданную параметром Path, и ждет ее завершения.
Во время выполнения внешней программы, текущее приложение скрывается (
т.к. не может перерисовать главное окно, что некрасиво), поэтому фактически
происходит переключение с текущей программы на внешнюю и,
после завершения внешней программы, обратно.
В качестве внешней программы может выступать любой выполняемый файл (EXE, COM, BAT, SCR).
Зависимости: Windows, Forms
Автор: Евгений Валяев (RhinoFC), rhinofc@sniiggims.ru, ICQ:55263922, Новосибирск
Copyright: RhinoFC
Дата: 5 июня 2002 г.
***************************************************** }
function SwitchToProg(const Path: string): Boolean;
var
SI: TStartupInfo;
PI: TProcessInformation;
ExitCode: Cardinal;
begin
FillChar(SI, SizeOf(SI), 0);
SI.cb := SizeOf(SI);
Result := CreateProcess(nil, PChar(Path), nil, nil, False, 0, nil, nil,
SI, PI);
if Result then
begin
Application.MainForm.Hide;
while GetExitCodeProcess(PI.hProcess, ExitCode) and
(ExitCode = STILL_ACTIVE) do
; // ждем завершения, пустой цикл
Application.MainForm.Show;
end;
end;
Как запустить приложение и подождать пока оно отработает3
Код: 
Unit exec;
interface
Uses Windows, SysUtils, Forms, ShellAPI;
function ExecWin(Path,name,CommandLine,CurrentDir:string;Wait:boolean) : word;
implementation
function ExecWin(Path,name,CommandLine,CurrentDir:string;Wait:boolean) : word;
var
tsi : TStartupInfo;
tpi : TProcessInformation;
tPath,Command : PChar;
CurDir :Pchar;
// st1 :string;
// T1,T2,T3,T4 :TFileTime;
// rr :boolean;
cod :DWord;
// ErrorMessage: Pointer;
// ErrorCode: DWORD; // holds a system error code
begin
Result := 30;
Path:=path+name+' '+CommandLine+#00;
CommandLine:=CommandLine+#0;
tPath := StrAlloc(512);
Command := StrAlloc(512);
CurDir :=StrAlloc(512);
FillChar(tsi, SizeOf(TStartupInfo), 0);
tsi.cb := SizeOf(TStartupInfo);
tsi.dwFlags := STARTF_USESHOWWINDOW;
tsi.wShowWindow := SW_SHOWMINNOACTIVE;
// FindExecutable(@Path[1],nil,tPath);
// st1:=string(tPath)+#0;
// st1:=AnsiUpperCase(st1);
// Path:=AnsiUpperCase(Path);
// if st1< > Path then st1:=Concat(st1,' ',path,#0);
// Move(st1[1],tPath[0],Length(st1));
// Move(CommandLine[1],Command[0],length(CommandLine));
Move(Path[1],tPath[0],Length(Path));
CurrentDir:=CurrentDir+#0;
Move(CurrentDir[1],CurDir[0],length(CurrentDir));
try
if CreateProcess(nil,@tPath[0]{, @Command[0]},nil, nil, False,
CREATE_NEW_CONSOLE or NORMAL_PRIORITY_CLASS,nil, @CurDir[0], tsi, tpi)
then begin
cod:=WAIT_TIMEOUT;
while (cod=WAIT_TIMEOUT) and Wait do begin
cod:=WaitForSingleObject(tpi.hProcess, 500);
Application.ProcessMessages;
end;
result:=0;
{ rr:=GetProcessTimes(tpi.hProcess,t1,t2,t3,t4);
while (t2.dwLowDateTime=0) and (t2.dwHighDateTime=0) and rr do begin
Application.ProcessMessages;
rr:=GetProcessTimes(tpi.hProcess,t1,t2,t3,t4);
end;}
CloseHandle(tpi.hProcess);
CloseHandle(tpi.hThread);
end
else result:=GetLastError;
finally
{ ErrorCode := GetLastError;
FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER or FORMAT_MESSAGE_FROM_SYSTEM,
nil, ErrorCode, 0, @ErrorMessage, 0, nil);
LocalFree(hlocal(ErrorMessage));}
StrDispose(Command);
StrDispose(tPath);
StrDispose(CurDir);
end;
end;
end.
Как запустить приложение и подождать пока оно отработает4
Код: 
function ExecuteAndWait(FileName: string; HideApplication: boolean): boolean;
var
StartupInfo: TStartupInfo;
ProcessInfo: TProcessInformation;
exitc: cardinal;
begin
FillChar(StartupInfo, sizeof(StartupInfo), 0);
with StartupInfo do begin
cb := Sizeof(StartupInfo);
dwFlags := STARTF_USESHOWWINDOW;
wShowWindow := SW_SHOW;
end;
if not CreateProcess(nil, PChar(FileName), nil, nil, false,
CREATE_NEW_CONSOLE or NORMAL_PRIORITY_CLASS, nil, nil,
StartupInfo, ProcessInfo) then result := false
else begin
if HideApplication then begin
Application.Minimize;
ShowWindow(Application.Handle, SW_HIDE);
WaitforSingleObject(ProcessInfo.hProcess, INFINITE);
end else
while WaitforSingleObject(ProcessInfo.hProcess, 100) =
WAIT_TIMEOUT do begin
Application.ProcessMessages;
if Application.Terminated
then TerminateProcess(ProcessInfo.hProcess, 0);
end;
GetExitCodeProcess(ProcessInfo.hProcess, exitc);
result := (exitc = 0);
if HideApplication then begin
ShowWindow(Application.Handle, SW_SHOW);
Application.Restore;
Application.BringToFront;
end;
end;
end;
procedure TForm1.Button1Click(Sender: TObject);
procedure SetEnabled(en: boolean);
var
i: integer;
begin
for i := 0 to Form1.ComponentCount - 1 do
if Form1.Components[i] is TControl then
(Form1.Components[i] as TControl).Enabled := en;
end;
begin
SetEnabled(false);
if not ExecuteAndWait(Edit1.Text, CheckBox1.Checked)
then ShowMessage('Возникли какие-то проблемы');
SetEnabled(true);
end;
Как запустить приложение и подождать пока оно отработает5
Код: 
function WinExecAndWait(Path: PChar; Visibility: Word): Word;
var
InstanceID: THandle;
Msg: TMsg;
begin
InstanceID := WinExec(Path, Visibility);
if InstanceID < 32 then { значение меньше чем 32 указывает на ошибку }
WinExecAndWait := InstanceID
else
repeat
while PeekMessage(Msg, 0, 0, 0, pm_Remove) do
begin
if Msg.message = wm_Quit then
Halt(Msg.WParam);
TranslateMessage(Msg);
DispatchMessage(Msg);
end;
until
GetModuleUsage(InstanceID) = 0;
WinExecAndWait := 0;
end;
|