2011-10-06 87 views
0

我正在開發一個windows窗體應用程序在c#.net 4.0中。 我想捕獲Windows註銷事件。SystemEvents.SessionEnd沒有觸發

下面是代碼:

public Form1() 
    { 
     InitializeComponent(); 

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

爲什麼心不是我的sessionEnding射擊?

回答

2
  1. 它取決於在gpedit.msc上設置的配置。

打開gpedit.msc,導航到計算機配置>管理模板>系統>關機選項,然後選擇關閉自動終止阻止或取消關機的應用程序。由於我的筆記本電腦配置讓它自動關機,所以不會觸發會話結束

  1. 也許你可以在上面移動你的代碼到其窗口的入口點(主)。

  2. 也許你可以覆蓋Windows消息。你可以在MSDN庫文檔中看到它。 http://msdn.microsoft.com/en-us/library/microsoft.win32.systemevents.sessionending.aspx

  3. 關機消息泵已經被其他軟件重新路由,而不是重新路由到您的應用程序

0

這可能是有用的人。

如果包含窗體關閉事件

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

然後SessionEnding不會被解僱,我只是encoutered這個問題,並糾正它

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

在這裏,我需要防止在ALT + F4形態接近命令,所以我添加了這個表單結束事件,導致了這個問題。所以我們可以在表單關閉事件中集成會話結束事件。 選項2 in Refered from stackoverflow answer