本文摘自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#中的arraylist是什么?
C#使用autoresetevent实现同步的详解及实例
C#与.net框架之间的关系是什么?C#程序的开发工具
通达oa 使用C#的socket编程来其替代原有操作的示例代码分享
C#中@用法的实例解析
详解C#生成随机数功能的代码示例
关于C#中三个关键字params,ref,out的详细介绍
具体介绍C#线程与线程池的区别
C# 7.0 语言新特性
C#网络编程的图文代码详解
更多相关阅读请进入《C#》频道 >>
清华大学出版社
作者:[美]克里斯琴·内格尔(Christian Nagel)著。出版时间:2019年3月。
转载请注明出处:木庄网络博客 » C#捕获windows关机事件,在系统关机前做一些自己想做的事的示例代码