怎么在C++程序被关闭时(比如点了控制台右上角的叉)调用函数

类似Windows编程中
WM_Destroy:的实现

需要调用 WINDOWS API函数:SetConsoleCtrlHandler函数,有关此函数的用法说明:https://msdn.microsoft.com/en-us/library/windows/desktop/ms686016(v=vs.85).aspx

#include "stdafx.h"
#include <stdio.h>
#include <windows.h>

BOOL CtrlHandler(DWORD fdwCtrlType);

int main(int argc, char *argv[])
{
if (SetConsoleCtrlHandler((PHANDLER_ROUTINE)CtrlHandler, TRUE))
{
printf("调用WINDOWS API函数-->SetConsoleCtrlHandler函数.\n");
while (1) {}
}
else
{
printf("ERROR: could not set control handler.\n");
}

system("pause");
return 0;
}

BOOL CtrlHandler(DWORD fdwCtrlType)
{
switch (fdwCtrlType)
{
/* handle the CTRL-C signal */
case CTRL_C_EVENT:
printf("CTRL-C event\n");
Beep(750, 300);
return TRUE;

/* handle the CTRL-BREAK signal */
case CTRL_BREAK_EVENT:
printf("CTRL-BREAK event\n");
Beep(900, 200);
return TRUE;

/* handle the CTRL-CLOSE signal */
case CTRL_CLOSE_EVENT:
printf("点击了控制台右上角的“X”\n");
Beep(600, 200);
return TRUE;

/* handle the CTRL-LOGOFF signal */
case CTRL_LOGOFF_EVENT:
printf("CTRL-LOGOFF event\n");
Beep(1000, 200);
return TRUE;

/* handle the CTRL-SHUTDOWN signal */
case CTRL_SHUTDOWN_EVENT:
printf("CTRL-SHUTDOWN event\n");
Beep(750, 500);
return TRUE;

default:
return FALSE;
}
}

温馨提示:内容为网友见解,仅供参考
无其他回答
相似回答