读书人

Win32控制台应用程序捕捉关闭事件解决

发布时间: 2012-03-30 17:32:09 作者: rapoo

Win32控制台应用程序捕捉关闭事件
VC++中Win32控制台程序如何在点击关闭的时候捕捉该事件?
网上给的例子里面很多的变量什么的根本就不知道怎么定义的,不给定义怎么用啊!
希望大侠们给点帮助,谢谢了

[解决办法]

C/C++ code
#include <Windows.h>#include <stdio.h>#include <stdlib.h>BOOL _ExitFlag = 0;BOOL WINAPI ConsoleHandler(DWORD msgType){    if (msgType == CTRL_C_EVENT)    {        printf("Ctrl-C!\n");        _ExitFlag = 1;        return TRUE;    }    else if (msgType == CTRL_CLOSE_EVENT)    {        printf("Close console window!\n");        _ExitFlag = 1;        /* Note: The system gives you very limited time to exit in this condition */        return TRUE;    }    /*        Other messages:        CTRL_BREAK_EVENT         Ctrl-Break pressed        CTRL_LOGOFF_EVENT        User log off        CTRL_SHUTDOWN_EVENT      System shutdown    */    return FALSE;}int main(void){    SetConsoleCtrlHandler(ConsoleHandler, TRUE);    /* Just doing something */    printf("Press Ctrl-C or [x] to close...\n");    for(; !_ExitFlag; Sleep(100));    return 0;}
[解决办法]
同意6楼,补充下更全面的 http://flycode.org/thread-1171-1-2.html
C/C++ code
#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" );        return( true );    // ctrl-close: confirm that the user wants to exit.     case CTRL_CLOSE_EVENT:         printf( "ctrl-close event\n\n" );        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" );        return false;     case CTRL_SHUTDOWN_EVENT:         printf( "ctrl-shutdown event\n\n" );        return false;     default:         return false;     } } void 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"); } 

读书人网 >C++

热点推荐