c++控制台也能捕捉事件喽,防止误关闭的函数~~
#include <windows.h> #include <stdio.h> bool ctrlhandler( DWORD fdwctrltype ) { switch( fdwctrltype ) { // handle the ctrl-c signal. case CTRL_C_EVENT: printf( "ctrl-c event\n\n" ); _sleep(2000); return( true ); // ctrl-close: confirm that the user wants to exit. case CTRL_CLOSE_EVENT: printf( "ctrl-close event\n\n" ); _sleep(2000); return( true ); // pass other signals to the next handler. case CTRL_BREAK_EVENT: printf( "ctrl-break event\n\n" ); return false; case CTRL_LOGOFF_EVENT: printf( "ctrl-logoff event\n\n" ); _sleep(2000); return false; case CTRL_SHUTDOWN_EVENT: printf( "ctrl-shutdown event\n\n" ); _sleep(2000); return false; default: return false; } } int main( void ) { if( SetConsoleCtrlHandler( (PHANDLER_ROUTINE) ctrlhandler, true ) ) { printf( "\nthe control handler is installed.\n" ); printf( "\n -- now try pressing ctrl+c or ctrl+break, or" ); printf( "\n try logging off or closing the console...\n" ); printf( "\n(...waiting in a loop for events...)\n\n" ); while( 1 ){ Sleep(100);} } else printf( "\nerror: could not set control handler"); }
CTRL_C_EVENT
一個Ctrl + C的信號被接收,該信號或來自鍵盤,或來自GenerateConsoleCtrlEvent
函數
CTRL_BREAK_EVENT
一個 Ctrl + Break
信號被接收,該信號或來自鍵盤,或來自GenerateConsoleCtrlEvent
函數
CTRL_CLOSE_EVENT
當用戶系統關閉Console時,系統會發送此信號到此
CTRL_LOGOFF_EVENT
當用戶退出系統時系統會發送這個信號給所有的Console程序。該信號不能顯示是哪個用戶退出。
CTRL_SHUTDOWN_EVENT
當系統將要關閉時會發送此信號到所有Console程序。