1

Since I code in Visual Studio (2015), there are three main ways to launch my app:

  1. Pressing F5 in VS ("Start debugging")
  2. Pressing Ctrl+F5 in VS ("Start without debugging")
  3. Run the app from outside VS

With methods 1 and 3 the app window closes when the app ends execution. With method 2 it waits for any key before closing.

How do I make it wait for any key in all 3 cases? I use all 3 launching methods.

I could detect if I'm in case 2, and if not, call Console.ReadKey(). But how to detect it?

I can detect case 1 by checking System.Diagnostics.Debugger.IsAttached. But I can't differentiate between cases 2 and 3.

I tried the following to differentiate between those two cases but in both cases the result is false:

Process currentProcess = Process.GetCurrentProcess();
string moduleName = currentProcess.MainModule.ModuleName;
bool isLaunchedFromVS = moduleName.Contains(".vshost");

Note: Another approach would be to call ReadKey in all cases, but then I would need to know how to disable the built-in keywait of case 2. And according to this question this isn't possible.

Related question:
Check if application was started from within Visual Studio - but it doesn't ask how to differentiate between cases 2 and 3.

Community
  • 1
  • 1
Stefan Monov
  • 11,332
  • 10
  • 63
  • 120
  • Why not wait for a character input in ALL cases and force close your program? – Khalil Khalaf Jul 23 '16 at 17:19
  • @FirstStep: But wait for only *one* character input. – Stefan Monov Jul 23 '16 at 17:20
  • Use `Console.ReadKey().KeyChar` for _one_ char read from console. Then maybe "_Do you want to exit the program? Y/N_" and force close your app if `Y`.. Or something like that. – Khalil Khalaf Jul 23 '16 at 17:20
  • @FirstStep OP wants to know if it is possible to avoid getting 2 prompts in case 2: one from the program and one that VS adds automatically. – BJ Myers Jul 23 '16 at 17:32
  • @BJMyers Right but not if he force close the app no? – Khalil Khalaf Jul 23 '16 at 17:34
  • @FirstStep: By force close you mean click the X button in the top right of the window? That's not very nice, the button is very small and I have to remember to do it this way. – Stefan Monov Jul 25 '16 at 12:45
  • No @StefanMonov I meant this: [**Command to close an application of console?**](http://stackoverflow.com/questions/5682408/command-to-close-an-application-of-console) – Khalil Khalaf Jul 25 '16 at 12:57
  • @FirstStep: Calling Environment.Exit(0) doesn't prevent the extra keywait. – Stefan Monov Jul 25 '16 at 13:03
  • Possible duplicate of [How can I detect if "Press any key to continue . . ." will be displayed?](http://stackoverflow.com/questions/7458932/how-can-i-detect-if-press-any-key-to-continue-will-be-displayed) – Stefan Monov Jul 25 '16 at 14:31

0 Answers0