在公司上班,下班時需要簽退,而我呢隔三差五就會忘那么一次。怎么辦呢,于是就想能不能捕獲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惹的貨;實在是不可思議。
大家有沒有什么好主意可以克服這兩個缺點呢?
新聞熱點
疑難解答