[英]Process Exits immediately if I redirect a Console Application written in Delphi in C# winform application
我有一個用Delphi編寫的控制台應用程序(Host.exe)。 我想在C#應用程序(WinForm)中重定向控制台應用程序的輸出。
如果使用以下命令,則可以毫無問題地調用(Host.exe),但由於其運行方式為(show-window,非常獨立),因此無法獲得輸出。
ProcessStartInfo pp = new ProcessStartInfo();
pp.WorkingDirectory = Path.GetDirectoryName(Application.ExecutablePath);
pp.FileName = Path.Combine(pp.WorkingDirectory, "Host.exe");
pp.CreateNoWindow = false;
pp.WindowStyle = ProcessWindowStyle.Normal;
pp.UseShellExecute = true;
using (Process pProcess = Process.Start(pp))
{
while ((pProcess != null) && (!pProcess.HasExited))
{
Application.DoEvents();
Thread.Sleep(updatefreq);
}
}
但是,如果嘗試捕獲輸出(重定向),則該過程將立即退出(HasExited = true,循環中斷,調試器顯示“僅一部分ReadProcessMemory或WriteProcessMemory請求已完成”)。
ProcessStartInfo pp = new ProcessStartInfo();
pp.WorkingDirectory = Path.GetDirectoryName(Application.ExecutablePath);
pp.FileName = Path.Combine(pp.WorkingDirectory, "Host.exe");
pp.UseShellExecute = false;
pp.RedirectStandardOutput = true;
pp.RedirectStandardInput = true;
pp.RedirectStandardError = true;
pp.CreateNoWindow = true;
pp.WindowStyle = ProcessWindowStyle.Hidden;
StreamReader outputReader = null;
using (Process pProcess = Process.Start(pp))
{
if (pProcess != null)
{
//StreamWriter inputWriter = pProcess.StandardInput;
//StreamReader errorReader = pProcess.StandardError;
outputReader = pProcess.StandardOutput;
}
while ((pProcess != null) && (!pProcess.HasExited))
{
string ss = null;
if (outputReader != null)
{
ss = outputReader.ReadLine();
}
if ((ss != null) && (2 < ss.Length))
{
string[] s = ss.Split('|');
if (3 == s.Length)
{
float global;
//float.TryParse(s[0], out local);
float.TryParse(s[1], out global);
RadioTracer.SetCurrentMsg(s[2]);
RadioTracer.SetCurrentStep((int)global);
}
}
Application.DoEvents();
Thread.Sleep(updatefreq);
}
}
我已經用谷歌搜索了很多,但是還沒有解決方案。 接下來的頁面也存在類似的問題,並且我嘗試了建議的解決方案,但沒有任何效果。
http://go4answers.webhost4life.com/Example/redirectstandardinput-a-32-bit-114440.aspx
非常感謝...這已經浪費了我很多時間。.我希望我能在這里找到解決方案。
編輯:即使我不使用任何ReadLine()或ReadToEnd()方法,問題仍然存在。 當“ UseShellExecute”設置為false時,Host.exe將立即退出。Host.exe應該進行一些大的計算(大約需要2分鍾,並且每隔幾秒鍾通過控制台WriteLine報告進度)。
我發現如果在C#中重定向輸出,以下幾行將導致錯誤。 我在Delphi中使用Console.pas單元,在該單元的初始化中,它將調用InitScreenMode過程。
Reset(Input);
Rewrite(Output);
StdIn := TTextRec(Input).Handle;
StdOut := TTextRec(Output).Handle;
我猜想在C#中將'UseShellExecute'設置為false時,控制台“ stdin / stdout”會“重置”或“重寫”會導致問題
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.