本例实现:
捕获windows关机事件,做好定时提醒。
用到了Microsoft.Win32命名空间中的SystemEvents类,它有一个静态的事件SessionEnding在系统注销或关机时发生,此事件只有在winform的程序下有效,而在控制台程序下面无效,不能激发事件;
另外,必须在程序推出时将加上的事件移除掉,否则就容易造成内存溢出。
1,关键代码:
 
using System;
using System.Collections.Generic;
using System.Windows.Forms;
using Microsoft.Win32;
namespace Shutdown
{
    static class Program
    { www.jb200.com
        /// <summary>
        /// 应用程序的主入口点。
        /// </summary>
        [STAThread]
        static void Main()
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            FormShutdown formShutdown = new FormShutdown();
            SystemEvents.SessionEnding += new SessionEndingEventHandler(formShutdown.SystemEvents_SessionEnding);
            Application.Run(formShutdown);
        }
    }
}
2,Form代码:
 
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using Microsoft.Win32;
namespace Shutdown
{
    public partial class FormShutdown : Form
    {
        const string MESSAGE_TXT = "您签退了吗?";
        const string MESSAGE_TITLE = "提示";
        public FormShutdown()
        {
            InitializeComponent();
        }
        internal void SystemEvents_SessionEnding(object sender, SessionEndingEventArgs e)
        {
            DialogResult result = MessageBox.Show(MESSAGE_TXT, MESSAGE_TITLE, MessageBoxButtons.YesNo);
            e.Cancel = (result == DialogResult.No);
        }
        private void FormShutdown_Load(object sender, EventArgs e)
        {
            this.Location = new Point(Screen.PrimaryScreen.WorkingArea.Width - 200, 0);
        }
        protected override void OnClosed(EventArgs e)
        {
            SystemEvents.SessionEnding -= new SessionEndingEventHandler(this.SystemEvents_SessionEnding);
            base.OnClosed(e);
        }
    }
}
说明:
在c#2.0 Windows2003环境下测试通过。
注意:在使用SystemEvents.SessionEnding事件时切记要在程序退出时移除事件。
不足:
1,无法捕获休眠时的事件。
2,此程序占用的内存太多了,这么个小功能居然占了12M的内存。
您可能感兴趣的文章:
C#入门学习笔记之事件和委托的实例
学习 asp.net 的事件与委托
Asp.Net事件模型总结
C# 事件处理学习心得
c# 委托与事件的小例子