首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > C语言 >

win32控制台程序关闭时怎么保存数据

2012-03-25 
win32控制台程序关闭时如何保存数据用c和c++混合模式写了一个程序,但是在退出的时候,想保存些数据。怎么保

win32控制台程序关闭时如何保存数据
用c和c++混合模式写了一个程序,   但是在退出的时候,想保存些数据。怎么保存呢?

办法1:让用户输入特定字符,然后再保存。     但是特别繁琐用户会觉得烦
办法2:用户可能直接用鼠标点x   来关闭。这时候该怎么保存呢?截获关闭窗口的事件,然后再作逻辑判断,然后保存?   但是具体是哪个呢?
 



[解决办法]
在main函数最后写保存代码
或者开一个函数保存数据,一旦程序中途跳出,调用它,由它保存数据后退出
[解决办法]
在main退出点完成数据保存。

即在 return之前写信息到文件即可。
[解决办法]
This is an example of the SetConsoleCtrlHandler function that is used to install a control handler.


When a CTRL+C signal is received, the control handler returns TRUE, indicating that it has handled the signal. Doing this prevents other control handlers from being called.

When a CTRL_CLOSE_EVENT signal is received, the control handler returns TRUE, causing the system to display a dialog box that gives the user the choice of terminating the process and closing the console or allowing the process to continue execution. If the user chooses not to terminate the process, the system closes the console when the process finally terminates.

When a CTRL+BREAK, CTRL_LOGOFF_EVENT, or CTRL_SHUTDOWN_EVENT signal is received, the control handler returns FALSE. Doing this causes the signal to be passed to the next control handler function. If no other control handlers have been registered or none of the registered handlers returns TRUE, the default handler will be used, resulting in the process being terminated.

Note that MyErrorExit is a placeholder for an application-defined function to display and handle error conditions.

BOOL CtrlHandler(DWORD fdwCtrlType)
{
switch (fdwCtrlType)
{
// Handle the CTRL+C signal.

case CTRL_C_EVENT:

Beep(1000, 1000);
return TRUE;

// CTRL+CLOSE: confirm that the user wants to exit.

case CTRL_CLOSE_EVENT:

return TRUE;

// Pass other signals to the next handler.

case CTRL_BREAK_EVENT:

case CTRL_LOGOFF_EVENT:

case CTRL_SHUTDOWN_EVENT:

default:

return FALSE;
}
}

void main(void)
{
BOOL fSuccess;

fSuccess = SetConsoleCtrlHandler(
(PHANDLER_ROUTINE) CtrlHandler, // handler function
TRUE); // add to list
if (! fSuccess)
MyErrorExit( "Could not set control handler ");
}
msdn里的一个例子,不过我没有test过,你可以试一下,其中CTRL_CLOSE_EVENT表示控制台窗口关闭。

热点排行