Why my console app gets stuck
In my current project, we have a console app that runs in the background and sends data to a frontend application. The app works great but sometimes it stops working and we need to press a key for it to continue. It turned out it was because of Windows Console’s Quick Mode feature. When a user clicks on the console window, it hangs the app execution to allow the user to select the text..
Fortunately, you can easily disable Quick Edit for your app:
1// http://msdn.microsoft.com/en-us/library/ms686033(VS.85).aspx
2[DllImport("kernel32.dll")]
3public static extern bool SetConsoleMode(IntPtr hConsoleHandle, uint dwMode);
4
5private const uint ENABLE_EXTENDED_FLAGS = 0x0080;
6
7private static void DisableQuickEditMode()
8{
9 // Disable QuickEdit Mode
10 // Quick Edit mode freezes the app to let users select text.
11 // We don't want that. We want the app to run smoothly in the background.
12 // - https://stackoverflow.com/q/4453692
13 // - https://stackoverflow.com/a/4453779
14 // - https://stackoverflow.com/a/30517482
15
16 IntPtr handle = Process.GetCurrentProcess().MainWindowHandle;
17 SetConsoleMode(handle, ENABLE_EXTENDED_FLAGS);
18}
19
20public static void Main(string[] args)
21{
22 DisableQuickEditMode();
23 // Do stuff
24}