程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> .NET網頁編程 >> C# >> 關於C# >> 使用c#捕獲windows的關機事件

使用c#捕獲windows的關機事件

編輯:關於C#

在公司上班,下班時需要簽退,而我呢隔三差五就會忘那麼一次。怎麼辦呢,於是就想能不能捕獲windows的關機事件,做一個程序讓它在關機的時候提醒我一下呢。

非常幸運很容易就找到了Microsoft.Win32命名空間下面的SystemEvents類,他有一個靜態的事件SessionEnding在系統注銷或者關機時發生,此事件只有在winform的程序下有效,而在控制台程序下面無效,不能激發事件;還有一點我們必須在程序推出時將加上的事件移除掉,否則就容易造成內存溢出。

關鍵代碼如下:

以下是引用片段:
using System;
using System.Collections.Generic;
using System.Windows.Forms;
using Microsoft.Win32;
namespace Shutdown
{
static class Program
{
/**////
/// 應用程序的主入口點。
///
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
FormShutdown formShutdown = new FormShutdown();
SystemEvents.SessionEnding += new SessionEndingEventHandler(formShutdown.SystemEvents_SessionEnding);
Application.Run(formShutdown);
}
}
}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的內存,這都是.Net framework惹的貨;實在是不可思議。

大家有沒有什麼好主意可以克服這兩個缺點呢?

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved