我有一个从GUI应用程序启动的控制台应用程序。控制台应用程序使用文件名参数来解析和处理。目前我能够捕获它的输出并将其显示在GUI应用程序中,但我希望能够向其发送命令以便控制甚至停止其执行。如何从GUI应用程序向控制台应用程序发送命令
如何向控制台应用程序发送命令或字符串或任何内容,最好使用为打开输出而打开的管道?
const
CReadBuffer = 2400;
var
saSecurity: TSecurityAttributes;
hRead: THandle;
hWrite: THandle;
suiStartup: TStartupInfo;
piProcess: TProcessInformation;
pBuffer: array[0..CReadBuffer] of AnsiChar;
dRead: DWord;
dRunning: DWord;
dWritten: DWord;
Command: String;
BytesLeft: Integer;
BytesAvail: Integer;
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;
Command := 'messageparser.exe c:\messagefile.msg';
UniqueString(Command);
if CreateProcess(nil, PChar(Command), @saSecurity,
@saSecurity, True, NORMAL_PRIORITY_CLASS, nil, nil, suiStartup, piProcess) then
begin
repeat
dRunning := WaitForSingleObject(piProcess.hProcess, 100);
Application.ProcessMessages;
repeat
dRead := 0;
if not PeekNamedPipe(hread, @pbuffer, CReadBuffer, @dRead, @BytesAvail, @BytesLeft) then
RaiseLastOSError;
if dRead <> 0 then
begin
ReadFile(hRead, pBuffer[0], CReadBuffer, dRead, nil);
pBuffer[dRead] := #0;
OemToCharA(pBuffer, pBuffer);
// do something with the data
// if a condition is present then do the following:
// WriteFile(hWrite, some_command, size_of_buffer, DWritten, nil);
end;
until (dRead < CReadBuffer);
until (dRunning <> WAIT_TIMEOUT);
CloseHandle(piProcess.hProcess);
CloseHandle(piProcess.hThread);
end;
CloseHandle(hRead);
CloseHandle(hWrite);
end;
然后在控制台侧,存在等待输入一个线程。下面是execute方法:
while not Terminated do
begin
ReadLn(Command);
// process command
Sleep(10);
end;
所以如果有关于如何做是正确的,我欢迎他们:)提示这是新的我。然而,无论何时我发送一个命令,它都会以我从ReadPipe读入pBuffer而不是命令的方式来进行。
希望这会有所帮助。
-
实测值基于由纳特尖端的溶液。
Bi-directional communication between gui and console
所以你有这两个应用程序的源代码?他们都是用德尔福写的吗? – fupsduck 2010-01-06 20:23:40
我添加了源代码。 – yozey 2010-01-06 22:27:42
用于发布源代码 - 在尝试提供帮助时发挥所有作用。 – fupsduck 2010-01-07 01:30:05