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

开发 后端
使用C++制作Windows的关机时遇到的最大问题就是:首先是使用这种方式不能捕获休眠时的事件,其次这个程序占用的内存太多了。

下面研究在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惹的货;实在是不可思议。

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

【编辑推荐】

  1. 简介学习C++总结之谈
  2. 对C++库函数进行学习探索总结笔记
  3. C++类库设计的基本构思与方法
  4. C++语言真的还有市场价值?
  5. C++类库设计的基本构思与方法
责任编辑:chenqingxiang 来源: wewill.cn
相关推荐

2010-01-26 15:51:06

C++变量

2010-01-25 13:31:27

C++程序

2011-08-08 16:49:07

自动关机SwitchOffWindows

2010-01-25 09:50:58

C++函数对象

2010-01-28 14:33:58

C++Test工具

2010-01-25 14:00:27

C++类

2010-01-22 14:20:17

Visual C++

2019-07-09 19:36:54

Windows 10Windows关机延迟

2023-10-30 11:45:44

FridaC++函数

2009-09-09 13:47:38

C++访问SqlCe

2010-01-11 13:52:32

Visual C++子

2010-01-18 17:14:50

C++语言

2010-01-20 09:54:27

C++数据类型

2021-10-11 11:53:07

C++接口代码

2019-12-04 14:30:43

事件日志Windows 10Windows

2010-01-15 16:25:48

学习C++

2010-01-15 19:28:59

C++

2009-01-19 09:40:53

JavaScript事件代理事件处理器

2010-01-28 10:33:10

C++开发程序

2023-11-13 17:01:26

C++编程
点赞
收藏

51CTO技术栈公众号