有些时刻我们能够想在Windows关机时纪录或处置惩罚一些事变,这里供应几种要领。
要领一:
/// <summary> /// 窗口历程的回调函数 /// </summary> /// <param name="m"></param> protected override void WndProc(ref Message m) { switch (m.Msg) { //此音讯在OnFormClosing之前 case WindowsMessage.WM_QUERYENDSESSION: //MessageBox.Show("WndProc.WM_QUERYENDSESSION.我要阻挠体系封闭!"); //this.Close(); //this.Dispose(); //Application.Exit(); m.Result = (IntPtr)1; //阻挠Windows注销、关机或重启 break; default: break; } base.WndProc(ref m); }
要领二:
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: //注销或关时机触发此事宜; //MessageBox.Show("阻拦用户封闭事宜!"); e.Cancel = false; break; case CloseReason.WindowsShutDown: e.Cancel = true; MessageBox.Show("阻拦关机事宜!"); break; default: break; } base.OnFormClosing(e); }
要领三:
//当用户试图注销或封闭体系时发作。 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; } } //假如把上面的事宜处置惩罚顺序修改成以下 //private void SystemEvents_SessionEnding(object sender, SessionEndingEventArgs e) // { // e.Cancel = true; // } //那会涌现什么情况,你点击开始菜单关机挑选注销、关机、或重新启动将会失效,电脑不能一般关机了,进一步的话把顺序做成Windows效劳,晕,开玩笑? //SessionEnded事宜同上,事宜参数类为SessionEndedEventArgs,同SessionEndingEventArgs比拟少了Cancel属性,Cancel属性同一些windows下的某些事宜差不多, 比方Form.Closing事宜,Control.Validating事宜。 //补充,假如须要猎取应用顺序须要的体系信息,能够接见System.Windows.Forms.SystemInformation类,这也是一个很有效的类,它供应了一组静态属性。
以上就是C#捕捉windows关机事宜,在体系关机前做一些本身想做的事的示例代码的细致内容,更多请关注ki4网别的相干文章!