我有一個從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