2013-04-11 79 views
0

我有,我知道沒有得到充分利用移動車約250筆記本電腦。我正在編寫一個程序,它寫入一個日誌文件來捕獲電源,並關閉事件。然而,當我嘗試陷阱立即關閉事件(用戶持有電源按鈕),我沒有得到的數據寫入到文本文件中。如何跟蹤電腦開機,關機和停機的關鍵

任何輸入都會有幫助。提前致謝。

代碼:

using System; 
using System.Collections.Generic; 
using System.ComponentModel; 
using System.Data; 
using System.Drawing; 
using System.Linq; 
using System.Text; 
using System.Windows.Forms; 
using System.IO; 
using Microsoft.Win32; 

    namespace Log 
    { 
     public partial class Form1 : Form 
     { 
      public Form1() 
      { 
       InitializeComponent(); 
      } 

      string CrLf = System.Environment.NewLine; 
      private static int WM_QUERYENDSESSION = 0x11; 
      private static int WM_ENDSESSION_CRITICAL = 0x40000000; 

      private static bool systemShutdown = false; 

      private void Form1_Load(object sender, EventArgs e) 
      { 
       Write_Data("[" + DateTime.Now.ToString() + "] " + "Power on");    
      } 


      protected override void WndProc(ref System.Windows.Forms.Message m) 
      { 

       if (m.Msg == WM_QUERYENDSESSION) 
       { 
        Write_Data("[" + DateTime.Now.ToString() + "] " + "Power off"); 
        systemShutdown = true; 
       } 
       // If this is WM_QUERYENDSESSION, the closing event should be 
       // raised in the base WndProc. 

        if (m.Msg == WM_ENDSESSION_CRITICAL) 
        { 
         Write_Data("[" + DateTime.Now.ToString() + "] " + "Critical power down"); 
         systemShutdown = true; 
        } 

        base.WndProc(ref m); 
      }  

      private void Write_Data(string str_Data) 
      { 
       using (StreamWriter output = new StreamWriter("../Log.txt", true)) 
       { 
        output.WriteLine(str_Data); 
       } 
      } 
     } 

    } 

回答

1

可能會更有意義閱讀系統事件日誌http://msdn.microsoft.com/en-us/library/system.diagnostics.eventlog.aspx,只是覺得當這些事件發生

或者,如果這是不理想的,而不是監聽關閉事件,鉤,到程序的終止,只是假設,如果該程序正在關閉,計算機正在關閉,並致電WRITE_DATA在那裏。需要注意的是一些在這個解決方案的SO線程"On Exit" for a Console Application不要Windows7的工作,並採取行動在控制檯/表格應用程序關閉不同

+0

我認爲這是最可行的解決方案感謝@djcrabhat – JMJ 2013-04-11 16:06:20