SetConsoleCtrlHandler routine issue

后端 未结 5 889
逝去的感伤
逝去的感伤 2021-02-18 21:43

I\'m writting a console application in C++.

I use SetConsoleCtrlHandler to trap close and CTRL+C button. This allows for all my threads to stop and exit properly.

<
5条回答
  •  [愿得一人]
    2021-02-18 21:52

    It looks like you can no longer ignore close requests on Windows 7.

    You do get the CTRL_CLOSE_EVENT event though, and from that moment on, you get 10 seconds to do whatever you need to do before it auto-closes. So you can either do whatever work you need to do in the handler or set a global flag.

    case CTRL_CLOSE_EVENT: // CTRL-CLOSE: confirm that the user wants to exit.
                           close_flag = 1;
                           while(close_flag != 2)
                             Sleep(100);
                           return TRUE;
    

    Fun fact: While the code in your CTRL_CLOSE_EVENT event runs, the main program keeps on running. So you'll be able to check for the flag and do a 'close_flag = 2;' somewhere. But remember, you only have 10 seconds. (So keep in mind you don't want to hang up your main program flow waiting on keyboard input for example.)

提交回复
热议问题