使用c关闭电源按钮测试

时间:2015-01-22 06:31:23

标签: c winapi

我正在使用下面的应用程序,当我按下cpu``电源按钮我的应用程序暂停几分钟,如我在下面app使用的5分钟。问题是我用睡眠(300000)停止几分钟但是每当我按下电源按钮时操作都没有执行,如果有的话请告诉我

#include <windows.h>  
#include <stdio.h>
#include <pthread.h>
#include <signal.h>
#include <sys/types.h>
#include <unistd.h>

#define SHUTDOWN_TEST
FILE *fp;

BOOL CtrlHandler( DWORD fdwCtrlType )
{
    time_t rawtime;
    struct tm * timeinfo;

    time (&rawtime);
    timeinfo = localtime (&rawtime);

    switch( fdwCtrlType )
    {
    // Handle the CTRL-C signal.
    case CTRL_C_EVENT:
        printf( "Ctrl-C event\n\n" );
        Beep( 750, 300 );
        return( TRUE );

        // CTRL-CLOSE: confirm that the user wants to exit.
    case CTRL_CLOSE_EVENT:
        Beep( 600, 200 );
        printf( "Ctrl-Close event\n\n" );
        return( TRUE );

        // Pass other signals to the next handler.
    case CTRL_BREAK_EVENT:
        Beep( 900, 200 );
        printf( "Ctrl-Break event\n\n" );
        return FALSE;

    case CTRL_LOGOFF_EVENT:
        Beep( 1000, 200 );
        printf( "Ctrl-Logoff event\n\n" );
        return FALSE;

    case CTRL_SHUTDOWN_EVENT:


        printf( "Ctrl-Shutdown event\n\n" );
        while(1)
        {    
            Sleep(300000);
        }

        Beep( 750, 500 );

        return FALSE;

    default:
        return FALSE;
    }
}

int main( void )
{
    fp = (fopen("C:\\shutdown.txt","w"));

#ifdef SHUTDOWN_TEST
    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 ){
            printf("I am running\n");
            Sleep(3000) ;
        }
    }
    else
    {
        printf( "\nERROR: Could not set control handler");
        return 1;
    }

    fclose(fp);
#else
    if (pid = fork())
    {
        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 ){
                //  printf("I am running\n");
                //  Sleep(3000) ;
            }
        }
    }
    else
    {

    }
#endif
    return 0;
}

1 个答案:

答案 0 :(得分:1)

无法在此类处理程序中阻止系统关闭。由于Windows Vista有一个新的API。

使用ShutdownBlockReasonCreate

您可以使用GetConsoleWindow获取请求的窗口句柄。

阅读此link以查看自Vista以来的更改。