2016-03-07 67 views
0

我寫了一個簡單的Windows服務來執行一些與PowerModelChanged相關的任務。但我不知道如何使用它。你們考慮我的流動代碼,並給我一些建議,請:如何在Windows服務應用程序中使用PowerModelChanged事件?

public partial class Service : ServiceBase 
    { 
     public Service() 
     { 
      InitializeComponent(); 
      this.CanHandlePowerEvent = true; 
      SystemEvents.PowerModeChanged += PowerModeChanged; 
     } 

     protected override void OnStart(string[] args) 
     { 
      Library.WriteUserLog("ON"); 
     } 

     protected override void OnStop() 
     { 
      Library.WriteUserLog("OFF"); 
     } 

     // Write log when user either logon or logoff 
     public void PowerModeChanged(object sender, PowerModeChangedEventArgs e) 
     { 
      switch (e.Mode) 
      { 
       case PowerModes.Resume: 
        Library.WriteUserLog("ON"); 
        break; 
       case PowerModes.Suspend: 
        Library.WriteUserLog("OFF"); 
        break; 
      } 
     } 
    } 

回答

0

試試這個(沒有測試它,但它應該是這樣的):

public partial class Service : ServiceBase 
    { 
     public Service() 
     { 
      InitializeComponent(); 
      this.CanHandlePowerEvent = true; 
     } 

     protected override void OnStart(string[] args) 
     { 
      Library.WriteUserLog("ON"); 
     } 

     protected override void OnStop() 
     { 
      Library.WriteUserLog("OFF"); 
     } 

     protected override bool OnPowerEvent(PowerBroadcastStatus powerStatus) 
     { 
      switch (powerStatus) 
      { 
       case PowerBroadcastStatus.ResumeSuspend: 
        Library.WriteUserLog("ON"); 
        break; 
       case PowerBroadcastStatus.Suspend: 
        Library.WriteUserLog("OFF"); 
        break; 
        // other statuses.... 
      } 
      return base.OnPowerEvent(powerStatus); 
     } 

     } 
    } 
+0

@VND謝謝您的回答,但它不能正常工作。你有什麼辦法來處理?! –

+0

@凱勒,你能澄清一下,什麼是不正確的,它應該是怎樣的?你收到任何錯誤消息嗎? – VDN

+0

看看[這個鏈接](http://stackoverflow.com/questions/16593100/what-is-the-proper-way-to-have-a-windows-service-stop-and-start-gracefully-什麼時候) – VDN

相關問題