龙盟编程博客 | 无障碍搜索 | 云盘搜索神器
快速搜索
主页 > 软件开发 > C/C++开发 >

如何使用C++制作Windows的关机事件

时间:2011-04-12 23:18来源:未知 作者:admin 点击:
分享到:
下面研究在C++里,使用C++捕获windows的关机事件,看看C++是否可以做一个程序,能让它在关机的时候提醒我一下呢,这样就不会在有的文件没保存下的情况下,关机导致的损失了。 非常

下面研究在C++里,使用C++捕获windows的关机事件,看看C++是否可以做一个程序,能让它在关机的时候提醒我一下呢,这样就不会在有的文件没保存下的情况下,关机导致的损失了。

非常幸运很容易就找到了Microsoft.Win32命名空间下面的SystemEvents类,他有一个静态的事件SessionEnding在系统注销或者关机时发生,此事件只有在winform的程序下有效,而在控制台程序下面无效,不能激发事件;还有一点我们必须在程序推出时将加上的事件移除掉,否则就容易造成内存溢出。

关键代码如下:

  1. using System;   
  2. using System.Collections.Generic;   
  3. using System.Windows.Forms;   
  4. using Microsoft.Win32;   
  5. namespace Shutdown   
  6. {   
  7. static class Program   
  8. {   
  9. /**////   
  10. /// 应用程序的主入口点。   
  11. ///   
  12. [STAThread]   
  13. static void Main()   
  14. {   
  15. Application.EnableVisualStyles();   
  16. Application.SetCompatibleTextRenderingDefault(false);   
  17. FormShutdown formShutdown = new FormShutdown();   
  18. SystemEvents.SessionEnding += new SessionEndingEventHandler(formShutdown.SystemEvents_SessionEnding);   
  19. Application.Run(formShutdown);   
  20. }   
  21. }   
  22. }Form 的代码:   
  23. using System;   
  24. using System.Collections.Generic;   
  25. using System.ComponentModel;   
  26. using System.Data;   
  27. using System.Drawing;   
  28. using System.Text;   
  29. using System.Windows.Forms;   
  30. using Microsoft.Win32;   
  31. namespace Shutdown   
  32. {   
  33. public partial class FormShutdown : Form   
  34. {   
  35. const string MESSAGE_TXT = "您签退了吗?";   
  36. const string MESSAGE_TITLE = "提示";   
  37. public FormShutdown()   
  38. {   
  39. InitializeComponent();   
  40. }  

此程序在使用C++在Windows2003下测试通过。大家在使用SystemEvents.SessionEnding事件时切记要在程序退出时移除事件。

不过有两点遗憾之处:

1. 使用这种方式不能捕获休眠时的事件

2. 这个程序占用的内存太多了,只有这么一个小功能居然占了12M的内存,这都是.Net framework惹的货;实在是不可思议。

大家有没有什么好主意可以克服这两个缺点呢?

精彩图集

赞助商链接