如何跟踪电脑开机,关机和停机的关键
问题描述:
我有,我知道没有得到充分利用移动车约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);
}
}
}
}
答
可能会更有意义阅读系统事件日志http://msdn.microsoft.com/en-us/library/system.diagnostics.eventlog.aspx,只是觉得当这些事件发生
或者,如果这是不理想的,而不是监听关闭事件,钩,到程序的终止,只是假设,如果该程序正在关闭,计算机正在关闭,并致电WRITE_DATA在那里。需要注意的是一些在这个解决方案的SO线程"On Exit" for a Console Application不要Windows7的工作,并采取行动在控制台/表格应用程序关闭不同
我认为这是最可行的解决方案感谢@djcrabhat – JMJ 2013-04-11 16:06:20