SystemEvents.SessionEnding not firing

匿名 (未验证) 提交于 2019-12-03 00:45:01

问题:

I am developing an windows forms application in c# .net 4.0. I want to capture windows logoff event.

Here is the code:

    public Form1()     {         InitializeComponent();          SystemEvents.SessionEnding += (s, e) =>         {             if (e.Reason == SessionEndReasons.Logoff)             {                 MessageBox.Show("LogOff");             }             else if (e.Reason == SessionEndReasons.SystemShutdown)             {                 MessageBox.Show("ShutDown");             }         };     } 

Why isnt my sessionEnding firing?

回答1:

  1. It depends on the configuration that is set on gpedit.msc.

Open gpedit.msc, navigate to Computer Configuration > Administrative Templates > System > Shutdown Options and choose Turn off automatic termination of applications that block or cancel shutdown. Since mine laptop configure make it automatic shutdown, so it will never fire session ending

  1. Perhaps you can move your code above into entry point of its windows (in the main).

  2. Perhaps you can override windows message. You can see it in MSDN library documentation. http://msdn.microsoft.com/en-us/library/microsoft.win32.systemevents.sessionending.aspx

  3. Shutdown message pump has been re route by other software and not re route to your apps



回答2:

This could be useful to someone.

if form close event is included

private void Form1_FormClosing(object sender, FormClosingEventArgs e)     {         e.Cancel = true;     } 

then SessionEnding will not be fired, i just encoutered this problem and rectified it

void SystemEvents_SessionEnding(object sender, Microsoft.Win32.SessionEndingEventArgs e)     {} 

here i need to prevent Form close upon Alt+F4 command, so i added this form closing event this resulted in this issue. so we can integrate session ending event in form close event. Option 2 in Refered from stackoverflow answer



标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!