本文摘自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# tabcontral选项卡中加载显示窗体后 实现单向参数传递测试代码示例(图)
深入理解C#rx的主要接口
详解C#接口在派生类和外部类中的调用方法示例
用C#描述数据结构1:统计代码执行时间对象的代码详解
C#控制台应用程序中如何输出彩色字体的详细介绍
asp.net实现分页(非控件,输出html代码)
dictionary字典类在C#中的示例代码介绍
c#中var和dynamic之间的区别是什么?
C#执行原理深入解析(图文)
详解kotlin中如何实现类似java或C#中的静态方法
更多相关阅读请进入《C#》频道 >>
清华大学出版社
作者:[美]克里斯琴·内格尔(Christian Nagel)著。出版时间:2019年3月。
转载请注明出处:木庄网络博客 » C#捕获windows关机事件,在系统关机前做一些自己想做的事的示例代码