gpt4 book ai didi

delphi - 执行后台程序并继续执行代码?

转载 作者:行者123 更新时间:2023-12-03 15:19:57 25 4
gpt4 key购买 nike

我想从我的 Delphi 代码运行后台应用程序。打开的应用程序是一个基于 DOS 的 EXE,它将内容输出到 DOS 窗口。该程序将无限期地打开,直到从任务管理器关闭为止。我当前用来打开应用程序的代码是;

procedure CaptureConsoleOutput(const ACommand, AParameters: String; CallBack: TArg<PAnsiChar>);
const
CReadBuffer = 2400;
var
saSecurity: TSecurityAttributes;
hRead: THandle;
hWrite: THandle;
suiStartup: TStartupInfo;
piProcess: TProcessInformation;
pBuffer: array [0 .. CReadBuffer] of AnsiChar;
dBuffer: array [0 .. CReadBuffer] of AnsiChar;
dRead: DWord;
dRunning: DWord;
begin
saSecurity.nLength := SizeOf(TSecurityAttributes);
saSecurity.bInheritHandle := True;
saSecurity.lpSecurityDescriptor := nil;

if CreatePipe(hRead, hWrite, @saSecurity, 0) then
begin
FillChar(suiStartup, SizeOf(TStartupInfo), #0);
suiStartup.cb := SizeOf(TStartupInfo);
suiStartup.hStdInput := hRead;
suiStartup.hStdOutput := hWrite;
suiStartup.hStdError := hWrite;
suiStartup.dwFlags := STARTF_USESTDHANDLES or STARTF_USESHOWWINDOW;
suiStartup.wShowWindow := SW_HIDE;

if CreateProcess(nil, pChar(ACommand + ' ' + AParameters), @saSecurity, @saSecurity, True, NORMAL_PRIORITY_CLASS, nil, nil, suiStartup, piProcess) then
begin
repeat
dRunning := WaitForSingleObject(piProcess.hProcess, 100);
//Application.ProcessMessages();
repeat
dRead := 0;
ReadFile(hRead, pBuffer[0], CReadBuffer, dRead, nil);
if(dRead > 0) then
begin
pBuffer[dRead] := #0;
//ShowMessage(pBuffer);
//OemToAnsi(pBuffer, pBuffer);
//Unicode support by Lars Fosdal
OemToCharA(pBuffer, dBuffer);
CallBack(dBuffer);
end;
until (dRead < CReadBuffer);
until (dRunning <> WAIT_TIMEOUT);
CloseHandle(piProcess.hProcess);
CloseHandle(piProcess.hThread);
end;
CloseHandle(hRead);
CloseHandle(hWrite);
end;
end;

这很好,但是因为程序不会“退出”并永远保持打开状态,所以我的应用程序挂起,并且代码永远不会移动。

如有任何帮助,我们将不胜感激

最佳答案

如果您不需要对生成的进程执行任何操作,只需关闭 CreateProcess() 返回的句柄并继续,该进程将继续运行。但由于您似乎需要连续读取生成进程的输出,因此您可以简单地将逻辑移至工作线程中,这样您的主代码就不会再被阻塞。

关于delphi - 执行后台程序并继续执行代码?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25212739/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com