2017-02-13 51 views
0

要爲我的應用程序編寫某種調試擴展,我試圖做一些可以創建一個新的控制檯窗口並向其寫入信息的東西。C# - 寫入一個新的控制檯窗口

我寫了一個非常簡單的ConsoleApplication,它基本讀取它接收到的輸入,直到它等於terminate

private static void Main(string[] args) 
{ 
    string text; 
    while ((text = Console.ReadLine()) != "terminate") 
    { 
     Console.WriteLine(text); 
    } 
} 

我加入這個ConsoleApplication到我的資源,然後寫了一個新的項目中:

// Create the temporary file 
string path = Path.Combine(Path.GetTempPath(), "debugprovider.exe"); 
File.WriteAllBytes(path, Properties.Resources.debugprovider); 

// Execute the file 
ProcessStartInfo startInfo = new ProcessStartInfo(); 
startInfo.UseShellExecute = false; 
startInfo.RedirectStandardInput = true; 
startInfo.FileName = path; 

Process process = new Process(); 
process.StartInfo = startInfo; 
process.Start(); 

process.StandardInput.WriteLine("Write a new line ..."); 
process.StandardInput.WriteLine("terminate"); 
process.WaitForExit(); 

當我的應用程序被關閉我也把這個刪除後的文件:

// Delete the temporary file as it is no longer needed 
File.Delete(path); 

我的問題是,我沒有看到窗口中的輸入,只存在一個空白的控制檯窗口。我怎樣才能解決這個問題?

+0

你需要這樣的東西' StreamWriter myStreamWriter = process.StandardInput; myStreamWriter.WriteLine(「Write a new line ...」); myStreamWriter.Close();' – Hackerman

+0

您的主項目也是一個控制檯應用程序嗎?所以你想在現有的控制檯窗口中看到產生的控制檯的輸入和輸出?我得到了像之前工作的東西,如[這裏](http://stackoverflow.com/a/38491255/5095502)所示,只需用''path'替換'FileName'並替換我的WriteLine與你的並且它應該做你想。 – Quantic

+0

@Quantic對不起,如果我沒有足夠說明我自己,我甚至沒有看到新產生的窗口中的輸入。我的新項目是一個WPF應用程序。 –

回答

1

如果你希望你的孩子的過程的輸出,那麼你將要標準輸出重定向到,聽過程OutputDataReceived事件:

,然後處理從process_OutputDataReceived孩子過程中的輸出:

void process_OutputDataReceived(object sender, DataReceivedEventArgs e) { 
    Console.Write(e.Data); 
} 
0

試試這個:

var path = Path.Combine(Path.GetTempPath(), "debugprovider.exe"); 
File.WriteAllBytes(path, Properties.Resources.debugprovider); 
using (var cmd = new Process()) 
{ 
    cmd.StartInfo = new ProcessStartInfo(path) 
    { 
     WindowStyle = ProcessWindowStyle.Hidden, 
     UseShellExecute = false, 
     RedirectStandardInput = true, 
     RedirectStandardOutput = true, 
     RedirectStandardError = true, 
     CreateNoWindow = true 
    }; 
    var outputStringBuilder = new StringBuilder(); 
    cmd.OutputDataReceived += (sender, e) => 
    { 
     if (!String.IsNullOrEmpty(e.Data)) 
     { 
      Console.WriteLine(e.Data); 
     } 
    }; 
    var errorStringBuilder = new StringBuilder(); 
    cmd.ErrorDataReceived += (sender, e) => 
    { 
     if (!String.IsNullOrEmpty(e.Data)) 
     { 
      Console.WriteLine(e.Data); 
     } 
    }; 
    cmd.Start(); 
    cmd.StandardInput.WriteLine("Write a new line ..."); 
    cmd.StandardInput.WriteLine("terminate"); 
    cmd.StandardInput.Flush(); 
    cmd.StandardInput.Close(); 
    cmd.BeginOutputReadLine(); 
    cmd.BeginErrorReadLine(); 
    cmd.WaitForExit(); 
}