| 发表于:2007-04-26 10:19:06 楼主 |
实现的功能是使用c#捕获windows的关机事件 捕获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惹的祸;实在是不可思议。 转http://dotnet.chinaitlab.com/ |
|
|
|
|