title: Why does closing a console that was started with AllocConsole cause my whole application to exit? Can I change this behavior?
body: <p>What I want to have happen is that the console window just goes away, or better yet that it is hidden, but I want my application to keep running. Is that possible? I want to be able to use Console.WriteLine and have the console serve as an output window. I want to be able to hide and show it, and I don't want the whole app to die just because the console was closed.</p>
  
  <p><strong>EDIT</strong></p>
  
  <p>Code:</p>
  
  <pre><code>internal class SomeClass {
  
      [DllImport("kernel32")]
      private static extern bool AllocConsole();
  
      private static void Main() {
          AllocConsole();
          while(true) continue;
      }
  }
  </code></pre>
  
  <p><strong>EDIT 2</strong></p>
  
  <p>I tried the accepted solution here [ <a href="https://stackoverflow.com/questions/474679/capture-console-exit-c-sharp">Capture console exit C#</a> ], per the suggestion in the comments on this question. The example code is bugged in that the DLLImport needs to be "kernel32.dll" or "kernel32", not "Kernel32". After making that change, I'm getting a message to my handler for CTRL_CLOSE_EVENT when I click the X on the console window. However, calling FreeConsole and/or returning true doesn't prevent the application from terminating.</p>