本文摘自PHP中文网,作者黄舟,侵删。
C#捕获windows关机事件,在系统关机前做一些自己想做的事;有些时候我们可能想在Windows关机时记录或处理一些事情,这里提供几种方法。
方法一:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 | /// <summary>
/// 窗口过程的回调函数
/// </summary>
/// <param name="m"></param>
protected override void WndProc( ref Message m)
{
switch (m.Msg)
{
case WindowsMessage.WM_QUERYENDSESSION:
m.Result = (IntPtr)1;
break ;
default :
break ;
}
base .WndProc( ref m);
}
|
方法二:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 | protected override void OnFormClosing(FormClosingEventArgs e)
{
switch (e.CloseReason)
{
case CloseReason.ApplicationExitCall:
e.Cancel = true ;
MessageBox.Show( "拦截关闭要求事件!" );
break ;
case CloseReason.FormOwnerClosing:
e.Cancel = true ;
MessageBox.Show( "拦截自身关闭事件!" );
break ;
case CloseReason.MdiFormClosing:
e.Cancel = true ;
MessageBox.Show( "拦截MDI窗体关闭事件!" );
break ;
case CloseReason.None:
break ;
case CloseReason.TaskManagerClosing:
e.Cancel = true ;
MessageBox.Show( "拦截任务管理器关闭事件!" );
break ;
case CloseReason.UserClosing:
e.Cancel = false ;
break ;
case CloseReason.WindowsShutDown:
e.Cancel = true ;
MessageBox.Show( "拦截关机事件!" );
break ;
default :
break ;
}
base .OnFormClosing(e);
}
|
方法三:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 | SystemEvents.SessionEnding += new SessionEndingEventHandler(SystemEvents_SessionEnding);
private void SystemEvents_SessionEnding( object sender, SessionEndingEventArgs e)
{
if (MessageBox.Show( this , "是否允许系统注销!" , "系统提示" , MessageBoxButtons.YesNo) != DialogResult.Yes)
{
e.Cancel = true ;
}
else
{
e.Cancel = false ;
}
SessionEndReasons reason = e.Reason;
switch (reason)
{
case SessionEndReasons.Logoff:
MessageBox.Show( "用户正在注销。操作系统继续运行,但启动此应用程序的用户正在注销。" );
break ;
case SessionEndReasons.SystemShutdown:
MessageBox.Show( "操作系统正在关闭。" );
break ;
}
}
比如Form.Closing事件,Control.Validating事件。
|
以上就是C#捕获windows关机事件,在系统关机前做一些自己想做的事的示例代码的详细内容!
相关阅读 >>
C#中反射是什么?
对比分析C#与java的区别
C#如何利用reportviewer来生成报表的示例代码分享(图)
C#中sealed关键字的作用详解
【C#教程】C# 枚举(enum)
c#cs与bs数据请求交换
C#学习记录:编写高质量代码改善整理建议1-3
C#中@用法的实例解析
C#如何连接数据库?oledbconnection与sqlconnection的区别
C#设计模式-派生类实现非虚接口陷阱的实例代码分享
更多相关阅读请进入《C#》频道 >>
清华大学出版社
作者:[美]克里斯琴·内格尔(Christian Nagel)著。出版时间:2019年3月。
转载请注明出处:木庄网络博客 » C#捕获windows关机事件,在系统关机前做一些自己想做的事的示例代码