2015-04-01 25 views
0

我在C#中構建了一個窗口應用程序,它將在任何切換用戶發生時通知我。現在使用「SessionSwitch」事件獲取通知。如何在window 7中發生「switch user」時得到通知

private void startLisning() 
{ 
     Microsoft.Win32.SystemEvents.SessionSwitch +=new Microsoft.Win32.SessionSwitchEventHandler(SystemEvents_SessionSwitch); 
     this.eventHandlerCreated = true; 
} 

private void SystemEvents_SessionSwitch(object sender, EventArgs e) 
{ 
     System.IO.File.AppendAllText(Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "testtest.txt"), "SwitchUser\t" + DateTime.Now.ToString() + Environment.NewLine); 


} 

但是在這種情況下,它也會在發生「UNLOCK」時發送通知。我不想要的。 我只需要當任何用戶在他的系統中切換用戶時,我的應用程序應該得到通知並將其記錄到日誌文件中。 只有在lock或switchUser發生時才應該記錄。

在此先感謝。

回答

0
private void Form1_Load(object sender, EventArgs e) 
    { 
     startLisning(); 
    } 
    private bool eventHandlerCreated; 

    private void startLisning() 
    { 
     Microsoft.Win32.SystemEvents.SessionSwitch +=new Microsoft.Win32.SessionSwitchEventHandler(SystemEvents_SessionSwitch); 
     SystemEvents.SessionSwitch += new SessionSwitchEventHandler(SystemEvents_SessionSwitch1); 

     this.eventHandlerCreated = true; 
    } 


    private void SystemEvents_SessionSwitch1(object sender, SessionSwitchEventArgs e) 
    { 
     switch (e.Reason) 
     { 
      case SessionSwitchReason.SessionLock: 
       System.IO.File.AppendAllText(Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "testtest.txt"), "LOCK\t" + DateTime.Now.ToString() + Environment.NewLine); 
       break; 
      case SessionSwitchReason.SessionLogon: 
       System.IO.File.AppendAllText(Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "testtest.txt"), "LOGIN\t" + DateTime.Now.ToString() + Environment.NewLine); 
       break; 
      case SessionSwitchReason.SessionUnlock: 
       System.IO.File.AppendAllText(Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "testtest.txt"), "UNLOCK\t" + DateTime.Now.ToString() + Environment.NewLine); 
       break; 
      case SessionSwitchReason.ConsoleConnect: 
       System.IO.File.AppendAllText(Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "testtest.txt"), "UnlockAfetSwitchUser\t" + DateTime.Now.ToString() + Environment.NewLine); 
       break; 
      case SessionSwitchReason.ConsoleDisconnect: 
       System.IO.File.AppendAllText(Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "testtest.txt"), "SwitchUser\t" + DateTime.Now.ToString() + Environment.NewLine); 

       break; 
     } 

    } 

這會在「切換用戶」發生時通知,並在「用戶恢復」時通知。 'SessionSwitchReason.ConsoleDisconnect'是當任何切換用戶發生時觸發的事件。這段代碼在windows7中測試過,並且工作正常。

此代碼在Appdata文件夾中創建一個「testtest.txt」日誌文件。 U可以通過使用Window + r並搜索'%appdata%'來到達那裏。

它登錄如下通知: 1. LOGIN與日期時間 2. LOCK與日期時間 3. UNLOCK與日期時間 與日期時間

日期時間 5. SWITCH USER RESUME 4. SWITCH USER
相關問題