Skip to main content

You are not logged in. Your edit will be placed in a queue until it is peer reviewed.

We welcome edits that make the post easier to understand and more valuable for readers. Because community members review edits, please try to make the post substantially better than how you found it, for example, by fixing grammar or adding additional resources and hyperlinks.

Required fields*

13
  • 1
    Don't mind at all. Note that Console.WriteLine will go the bit-bucket with this solution if you double-clicked on the app. Also, you can check Marshal.GetLastWin32Error if you care when the attach failed. Commented Aug 26, 2011 at 18:11
  • 1
    @PeeHaa Thanks, this works quite well, however it seems that for me it is running in a separate thread (e.g. the command prompt returns immediately without waiting for the processing that started in Main to complete. Is that expected? Commented Jul 10, 2013 at 14:24
  • 1
    'using System.Runtime.InteropServices;' is needed to be able to use 'DllImport'. Commented Jun 24, 2014 at 8:52
  • 3
    The drawback with AttachConsole is that the cmd call will return immediately before the console is even attached and therefore before the output is written. This is also the reason why you need an additional enter key at the end. If you want to pipe or redirect the output somewhere, you will only get an empty output. I have not found a real solution this far. The given solution is not applicable for me but is the closest one. Commented Mar 21, 2016 at 16:04
  • 1
    So I'm attempting to do just this but what I'm experiencing is when I run my application from a command prompt with command line arguments it runs as it should, however, it returns control to the command prompt right away. I'm expecting it to run until the end and return an exit code. I'm using Environment.Exit(-1) for errors and (0) for success but with it returning right away that's not going to work out correctly. Commented Jul 23, 2018 at 19:59