C++ Win32控制台应用程序捕捉关闭事件

古城微笑少年丶 2022-04-11 05:56 420阅读 0赞

参考
[url]http://blog.sina.com.cn/s/blog\_690878d50101ls05.html\[/url\]

没有什么好解释的,直接看代码吧

  1. #include <iostream>
  2. #include <sstream>
  3. using namespace std;
  4. BOOL ConsoleEventHandler(DWORD dwCtrlType)
  5. {
  6. switch(dwCtrlType)
  7. {
  8. case CTRL_C_EVENT:// handle the ctrl-c signal
  9. {
  10. printf( "ctrl-c event\n\n" );
  11. return TRUE;
  12. }
  13. case CTRL_CLOSE_EVENT:// ctrl-close: confirm that the user wants to exit.
  14. {
  15. printf( "ctrl-close event\n\n" );
  16. return TRUE;
  17. }
  18. case CTRL_BREAK_EVENT:// pass other signals to the next handler.
  19. {
  20. printf( "ctrl-break event\n\n" );
  21. return TRUE;
  22. }
  23. case CTRL_LOGOFF_EVENT:
  24. {
  25. printf( "ctrl-logoff event\n\n" );
  26. return FALSE;
  27. }
  28. case CTRL_SHUTDOWN_EVENT:
  29. {
  30. printf( "ctrl-shutdown event\n\n" );
  31. return FALSE;
  32. }
  33. default:
  34. {
  35. return FALSE;
  36. }
  37. }
  38. }
  39. void main()
  40. {
  41. if(SetConsoleCtrlHandler((PHANDLER_ROUTINE)ConsoleEventHandler, true ))
  42. {
  43. printf( "\nthe control handler is installed.\n" );
  44. printf( "\n -- now try pressing ctrl+c or ctrl+break, or" );
  45. printf( "\n try logging off or closing the console...\n" );
  46. printf( "\n(...waiting in a loop for events...)\n\n" );
  47. while(TRUE)
  48. {
  49. //Do not let me go baby
  50. Sleep(5000);
  51. }
  52. }
  53. else
  54. {
  55. printf( "\nerror: could not set control handler");
  56. }
  57. }

发表评论

表情:
评论列表 (有 0 条评论,420人围观)

还没有评论,来说两句吧...

相关阅读

    相关 (1)C# 创建控制台应用程序

    在学习C\语言的时候,首先要学习控制台的应用程序,这样才能专注于语言的学习,减少学习的梯度,也有利于输出自己需要输出的内容。因此第一步学习C\语言时,一定要先使用控制台的应用程

    相关 win32学习06.控制台调试

    如果用Linux和DOS程序写C语言,写的时候断点调试,运行的时候使用输出调试,窗口程序下一般会使用写日志调试。如果我们依然希望使用输出调试也是可以的。 HANDLE