Pause Before Exiting a Console Application
A console application should always be designed to do whatever it is supposed to do and then exit without asking the user to press any key. The reason for this is that console applications are often used within scripts to automate several tasks. Obviously, you don’t want one console application launched by the script to wait until the user presses any key because that would be against the whole purpose of writing that script in the first place. However, sometimes it might be useful to pause the console application right before exiting. I wrote a small article that explains a way to add this support to your application elegantly without breaking support for scripting.
The article also shows how to detect that a new console was spawned on Windows. When you have a console application on Windows and you launch it by double-clicking its icon in Windows Explorer, a new console will be created but will disappear at the end of the execution and you probably won’t be able to read anything from the console. However, when you run your console application by typing the command in an existing console, your application will write all its output to that console and, when finished, you will be returned to the console prompt without the console being closed. There is a trick that can be used on Windows to automatically detect whether a new console window was opened or if your application was started from inside an existing console. The trick is to find out the cursor position in your console at the very beginning of your program. If the cursor position is (0,0), it is highly likely that a new console window was spawned. The article contains some source code to demonstrate this trick.