title: Howto return proper exit Code with AttachConsole from a Windows Forms in C#
body: <p>I 'am trying to exit a Windows Forms Application with returning the proper exitcode to the attached Console. For Testing i created a simple windows form app with this program.cs. I did take a look at other similar questions here at stackoverflow, but couldn't find a solution so far..</p>
  
  <p>if i test the app in a cmdbox with "ExitTest -test" it should return 84 as errorlevel instead of 0. How can i achieve this ?</p>
  
  <p>I use this code:</p>
  
  <pre><code>using System;
  using System.Collections.Generic;
  using System.Linq;
  using System.Runtime.InteropServices;
  using System.Threading.Tasks;
  using System.Windows.Forms;
  
  namespace ExitTest
  {
      static class Program
      {
          private const int AttachParentProcess = -1;
  
          [DllImport("kernel32.dll", SetLastError = true)]
          private static extern bool AttachConsole(int dwProcessId);
  
          [STAThread]
          static int Main()
          {
              int returncode = 0;
              if (Environment.GetCommandLineArgs().Length &gt; 1)
              {
                  // Attach Console to Gui
                  AttachConsole(AttachParentProcess);
                  Console.WriteLine("This is written to the console");
  
                  //Test ExitCode
                  returncode = 84;
  
                  // Sent enter to prevent waiting of Console on Close
                  SendKeys.SendWait("{ENTER}");
                  Environment.ExitCode = returncode;
              }
              else
              {
                  Application.EnableVisualStyles();
                  Application.SetCompatibleTextRenderingDefault(false);
                  Application.Run(new Form1());
  
              }
              return returncode;
          }
      }
  }
  </code></pre>