title: Console output in winforms GUI application
body: <p>all!</p>
  
  <p>Please, help me with any advice with my problem: I build GUI WinForms application and now I want to attach console to it. I found this is not as much easy as it seems before. But I found good solution here: <a href="https://stackoverflow.com/questions/4362111/how-do-i-show-a-console-output-window-in-a-forms-application">How do I show a console output/window in a forms application?</a> Below the code from <a href="https://stackoverflow.com/users/2530944/rag">rag</a> answer.</p>
  
  <pre><code>using System;
  using System.Runtime.InteropServices;
  
  namespace SomeProject
  {
      class GuiRedirect
      {
      [DllImport("kernel32.dll", SetLastError = true)]
      private static extern bool AttachConsole(int dwProcessId);
      [DllImport("kernel32.dll", SetLastError = true)]
      private static extern IntPtr GetStdHandle(StandardHandle nStdHandle);
      [DllImport("kernel32.dll", SetLastError = true)]
      private static extern bool SetStdHandle(StandardHandle nStdHandle, IntPtr handle);
      [DllImport("kernel32.dll", SetLastError = true)]
      private static extern FileType GetFileType(IntPtr handle);
  
      private enum StandardHandle : uint
      {
          Input = unchecked((uint)-10),
          Output = unchecked((uint)-11),
          Error = unchecked((uint)-12)
      }
  
      private enum FileType : uint
      {
          Unknown = 0x0000,
          Disk = 0x0001,
          Char = 0x0002,
          Pipe = 0x0003
      }
  
      private static bool IsRedirected(IntPtr handle)
      {
          FileType fileType = GetFileType(handle);
  
          return (fileType == FileType.Disk) || (fileType == FileType.Pipe);
      }
  
      public static void Redirect()
      {
          if (IsRedirected(GetStdHandle(StandardHandle.Output)))
          {
              var initialiseOut = Console.Out;
          }
  
          bool errorRedirected = IsRedirected(GetStdHandle(StandardHandle.Error));
          if (errorRedirected)
          {
              var initialiseError = Console.Error;
          }
  
          AttachConsole(-1);
  
          if (!errorRedirected)
              SetStdHandle(StandardHandle.Error, GetStdHandle(StandardHandle.Output));
      }
  }
  </code></pre>
  
  <p>This code works as charm except one downside: non-latin letters outputs to console in strange encoding (but if redirected to file, they are in right encoding). I need to redirect both StdOut and StdErr, and if I change any part of the code it stops redirecting.</p>