gpt4 book ai didi

c - 使用 c 关闭电源按钮测试

转载 作者:行者123 更新时间:2023-11-30 15:25:10 25 4
gpt4 key购买 nike

每当我按下 cpu` 电源按钮时,我都会使用下面的应用程序,我的应用程序会暂停几分钟,例如 5 分钟,因为我在下面使用的应用程序。问题是我使用 sleep(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;
}

最佳答案

无法在此类处理程序内阻止系统关闭。从 Windows Vista 开始,出现了一个新的 API。

使用ShutdownBlockReasonCreate

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

阅读此内容 link查看自 Vista 以来的变化。

关于c - 使用 c 关闭电源按钮测试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28082545/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com