是否可以重定向附加应用程序的控制台输出?

时间:2012-11-22 09:01:04

标签: c# console-application io-redirection

我有一个控制台应用程序将stdout重定向到文件,如下所示:

private static void Main()
{
  Console.SetOut(new StreamWriter("redirect.txt") {AutoFlush = true});

  Console.Title = "MyConsoleApp";
  Console.Error.WriteLine("This goes from console app to console");
  Console.WriteLine("This goes from console app to file");
  Console.ReadLine();
}

按预期工作,控制台显示一行文本,另一行显示在文件中。

我还有第二个连接到控制台的Winforms应用程序:

[DllImport("user32.dll", EntryPoint = "FindWindow", SetLastError = true)]
private static extern IntPtr FindWindowByCaption(IntPtr zeroOnly, string lpWindowName);

[DllImport("user32.dll", SetLastError = true)]
private static extern uint GetWindowThreadProcessId(IntPtr hWnd, out uint lpdwProcessId);

[DllImport("kernel32.dll", SetLastError = true)]
private static extern bool AttachConsole(uint dwProcessId);

private void AttachAndWrite()
{
  IntPtr h = FindWindowByCaption(IntPtr.Zero, "MyConsoleApp");
  uint p;
  GetWindowThreadProcessId(h, out p);
  if(AttachConsole(p))
    Console.WriteLine("I want this go to redirect.txt, but it ends up in the console window.");
}

Console.Writeline的输出现在进入控制台窗口,而不是我预期的文件。

  1. 为什么?
  2. 可以修复吗?

0 个答案:

没有答案