0

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

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. 可以修复吗?
4

0 回答 0