Code stops executing when a user clicks on the console window

前端 未结 2 1842
悲&欢浪女
悲&欢浪女 2021-02-01 22:06

I\'ve got a console application that executes my code without user interaction. If the user clicks within the console window, on purpose or on accident, all execution stops. <

2条回答
  •  清歌不尽
    2021-02-01 22:36

    I just saw that this answer linked in the comments of OP's question contained what I found by myself. I will keep my answer because people might not see it, just like me, and it would spare them a lot of time.


    Jim's answer did not work for me, I couldn't figure out why. I dug around and found a solution that works, so I'll share my findings, hopefully helping someone in the same situation.

    The problem was with the handle that I got from GetConsoleWindow(), it gave a Win32 error (0x6) where the handle is invalid when I tried to use it. The call to SetConsoleMode() did nothing.

    To get a working handle, I used GetStdHandle() to get the Input handle for the console. Add this to Jim's code :

    public const int STD_INPUT_HANDLE = -10;
    
    [DllImport("Kernel32.dll", SetLastError = true)]
    public static extern IntPtr GetStdHandle(int nStdHandle);
    

    Then replace GetConsoleWindow() by GetStdHandle(STD_INPUT_HANDLE) in DisableQuickEdit() and EnableQuickEdit() in Jim's code.

    After calling DisableQuickEdit(), the selection is disabled in the console.

    Thanks Jim !

提交回复
热议问题