一个可以统计电脑最近两个月每天的详细使用情况的程序,并且可以统计出上一个月的总用电量(方便分配宿舍里每个人应交的电费)。代码参考了过纯中先生 的PC_PowerOn_Time程序的源码。在此向他表示感谢!在这里公布代码及详细注释,供有兴趣的编程爱好者学习,请勿商用,否则后果很严重!
using System; //调用系统的API
using System.Drawing; //msdn这样描述: System.Drawing 命名空间提供了对 GDI+ 基本图形功能的访问
using System.Diagnostics; //msdn解释的比价含糊,我估计与跟踪系统日志的消息有关,下面遍历的时候会用到。注释掉这一句后仍然可以//编译运行。
using System.Collections; //msdn没有明确的解释,似乎是枚举,注释掉这一句后仍然可以编译运行
using System.ComponentModel; //Component就是组件的意思,应该和开发界面有关,注释掉它后仍然可以编译运行
using System.Windows.Forms; //表格
using System.Data; //系统数据类型,注释掉它后仍然可以编译运行
using System.IO; //这个看得出来就是跟系统输入输出有关的了
//
小结:上面几句看来比较关键的是System,System.Drawing,System.Windows.Forms,System.IO。而我们需要用的主要就是System里的API。
namespace PC_PowerOn_Time
{
/// <summary>
/// MainForm 的摘要说明。
/// </summary>
public class MainForm : System.Windows.Forms.Form //界面生成后执行下面的代码
{
internal System.Diagnostics.EventLog evLog; //导入系统时间日志
private System.Windows.Forms.ListView listView; //表格
private System.Windows.Forms.ColumnHeader ch_StartTime; //“开机时间”表格项
private System.Windows.Forms.ColumnHeader ch_PowerOffTime;//“关机时间”表格项
private System.Windows.Forms.ColumnHeader ch_RunningTime;//“运行时间”表格项
private System.Windows.Forms.MenuItem menuItem_About; //菜单
private System.Windows.Forms.ContextMenu contextMenu; //菜单
System.Resources.ResourceManager LocRM = new /*定义一个资源管理器*/
System.Resources.ResourceManager("PC_PowerOn_Time.InCodeStrings",typeof(MainForm).Assembly);
private System.Windows.Forms.MenuItem menuItem_ExportDetail; //定义一个菜单项
private System.Windows.Forms.MenuItem menuItem_ExportDays; //定义一个菜单项
private System.Windows.Forms.ToolTip toolTip; //定义工具提示
private System.ComponentModel.IContainer components;
//小结:上面四句都是跟程序右键弹出的菜单有关,可以不必理会。
public MainForm() //开始设计这个窗口
{
//
// Windows 窗体设计器支持所必需的
//
InitializeComponent(); //初始化组件
DateTime start = new DateTime(), stop = new DateTime(), prev_start = new DateTime();//定义开机时间、关机时间为DataTime类型,还有一个prev_start记录上一个记录的时间,三个的初始值都是当前时 间
TimeSpan dayOnTime = new TimeSpan(); //这个就是每天的总运行时间!!!
TimeSpan totaltime =new TimeSpan(); //记录这个月的总运行时间
foreach (System.Diagnostics.EventLogEntry ele in evLog.Entries) //foreach根据字面含义应该是一个遍历函数,对Eventlog时间日志里的每一项进行遍历,找出ID=6005和6006的项,6005对应开 机时间,6006对应关机时间
{
if(ele.Source == "EventLog") //当遍历的项是EventLog里面的项的时候,这个我觉得效率很低,因为它对整个事件日志都作了遍历,而我们要找的只是系统事件日志,不知道以后能不 能直接限定就在EventLog里面查找,而不是用if来判断
{
if(ele.EventID == 6005) // 开机服务
{
prev_start=start; //把start的值赋给它,也就是上一个记录的时间
start = ele.TimeGenerated; //获取与这个事件对应的时间,即开机时间
}
if(ele.EventID == 6006) // 关机服务
{
stop = ele.TimeGenerated; //获取与这个事件对应的时间,即关机时间
//下面要计算一天的总运行时间,应该先判断上个记录和这个记录是不是在同一天,以决定是要在上个记录的基础上加这一次的时间还是直接等于这个记录所对应的时间
if(prev_start.Day != start.Day && prev_start.Year != 1 &&start.Month==DateTime.Now.Month-1)
//先计算上一个月的运行时间。如果不是同一天,这一天的运行时间直接等于这个记录所对应的运行时间。而上一个记录就是这个记录前一天的最后一次执行机器的记录。所以我们可以先对前一天的总时间进行计算。执行以下语句
{
ListViewItem lviSub = new ListViewItem(); //声明一行表格
//先写前一天的机器总开机时间
lviSub.BackColor = Color.AliceBlue; //表格底色设置为浅蓝色,以突出总时间(很浅,不仔细看以为是白色)
//先记录前一天对应的年、月、日以及星期几
lviSub.SubItems[0].Text = prev_start.ToString(Application.CurrentCulture.DateTimeFormat.LongDatePattern)
+ "/t" + prev_start.DayOfWeek.ToString(Application.CurrentCulture);
lviSub.SubItems[0].Font = new Font(lviSub.SubItems[0].Font, FontStyle.Bold);
lviSub.SubItems.Add(LocRM.GetString("Running Time:")); //在第二栏添加“运行时间”字样
totaltime += dayOnTime; //计算一个月总运行时间
lviSub.SubItems.Add(dayOnTime.ToString()); //添加日期
dayOnTime = stop-start; //计算那一天的运行时间
listView.Items.Add(lviSub); //添加这一行的数据进入表格
}
//计算这个月的运行时间,代码和上面的类似,只是不需要计算一个月的总运行时间,所以没有totaltime += dayOnTime;这一句
else if (prev_start.Day != start.Day && prev_start.Year != 1 && start.Month == DateTime.Now.Month)
{
ListViewItem lviSub = new ListViewItem();
lviSub.BackColor = Color.AliceBlue;
lviSub.SubItems[0].Text = prev_start.ToString(Application.CurrentCulture.DateTimeFormat.LongDatePattern)
+ "/t" + prev_start.DayOfWeek.ToString(Application.CurrentCulture);
lviSub.SubItems[0].Font = new Font(lviSub.SubItems[0].Font, FontStyle.Bold);
lviSub.SubItems.Add(LocRM.GetString("Running Time:"));
lviSub.SubItems.Add(dayOnTime.ToString());
dayOnTime = stop - start;
listView.Items.Add(lviSub);
}
//如果是在同一天,那么这个记录所对应的那一天的运行时间就等于上一个记录的运行时间加上这个记录的运行时间(可能还会继续加下一个记录,如果下一个记录和这个记录同一天),即dayOnTime=dayOnTime+(stop-start);
else
{
dayOnTime += stop-start; //这个记录对应的那一天的运行时间(可能还会继续加)
}
//接下来我们要添加每一次开机和关机对应的时间以及运行的时间
ListViewItem lvi = new ListViewItem(); //声明一个表单项lvi
lvi.SubItems[0].Text = start.ToString("F"); //在lvi中添加开机时间
lvi.SubItems.Add( stop.ToString("F") ); //在lvi中添加关机时间
lvi.SubItems.Add((stop - start).ToString() ); //在lvi中添加运行时间
listView.Items.Add(lvi); //把lvi里的数据添加数据进表格
}
}
}
//小结:从上面我们可以获得几个比较有用的数据,某一个记录对应的年,月,日和星期分别为:.Year,.Month,.Day,DayOfWeek
//有了这几个数据我们接下来进行统计的时候就方便多了。
//遍历完后只剩下今天还没有计算出来了,我们要计算今天的运行时间,今天的运行时间比较特殊,因为我们现在没有关机,也就是少一个ID6006的事件。今天的运行时间就等于当前的时间减去开机时间,如果今天还运行过几次机器,那么就要再加上前几次运行的时间。
if(prev_start.Day != start.Day && prev_start.Year != 1)
{
ListViewItem lviSub = new ListViewItem(); //先把昨天的运行时间添加进表单
lviSub.BackColor = Color.AliceBlue;
lviSub.SubItems[0].Text = prev_start.ToString(Application.CurrentCulture.DateTimeFormat.LongDatePattern)
+ " " + prev_start.DayOfWeek.ToString(Application.CurrentCulture);
lviSub.SubItems[0].Font = new Font(lviSub.SubItems[0].Font, FontStyle.Bold);
lviSub.SubItems.Add(LocRM.GetString("Running Time:"));
lviSub.SubItems.Add(dayOnTime.ToString()); //到这里昨天的一切数据都已经放进了表单项,就等放入表单
dayOnTime = DateTime.Now-start; //这个就是我们本次开机到现在的运行时间
listView.Items.Add(lviSub); //把表单项放入表单
}
else
{
dayOnTime += DateTime.Now-start; //计算今天的总运行时间
}
//下面就是计算今天的运行时间了
listView.Items.Add(new ListViewItem(new string[] { start.ToString("F"),
DateTime.Now.ToString("F"),
(DateTime.Now-start).ToString().Substring(0, 8), })); //依然是增加一行表单
ListViewItem lviTodaySub = new ListViewItem(); //声明一个表单项
lviTodaySub.BackColor = Color.LightBlue; //底色设成浅蓝(这个浅蓝颜色比较清楚,强调是今天)
lviTodaySub.SubItems[0].Text = start.ToString(Application.CurrentCulture.DateTimeFormat.LongDatePattern)
+ "/t" + start.DayOfWeek.ToString(Application.CurrentCulture); //添加年月日和星期
lviTodaySub.SubItems[0].Font = new Font(lviTodaySub.SubItems[0].Font, FontStyle.Bold); //设置字体
lviTodaySub.SubItems.Add(LocRM.GetString("Running Time:")); //添加“运行时间”字样
lviTodaySub.SubItems.Add(dayOnTime.ToString().Substring(0, 8)); //添加这一天的运行时间
listView.Items.Add(lviTodaySub); //把这一行表单项添加进表单里面
//下面输出上一个月份的运行时间
int lastmonth = DateTime.Now.Month - 1; //记录上个月的数字
//MessageBox.Show(lastmonth.ToString()+"月 日~"+last.Day.ToString()+"日总运行时间为:" + totaltime.TotalHours.ToString()+"个小时"); //是否弹出一个对话框输出结果,取消注释就会另外弹出对话框输出结果
ListViewItem lresult = new ListViewItem();
lresult.BackColor = Color.Green;
lresult.SubItems[0].Text = lastmonth.ToString()+"月日~"+last.Day.ToString()+"日" ;
lresult.SubItems[0].Font = new Font(lviTodaySub.SubItems[0].Font, FontStyle.Bold);
lresult.SubItems[0].ForeColor=Color.White;
lresult.SubItems.Add("月总运行时间:");
lresult.SubItems.Add(totaltime.TotalHours.ToString()+"个小时"); //TotalHours的作用是将Timespan转换为小时数
listView.Items.Add(lresult);
}
//总结:利用系统日志完成计算主要是以遍历的形式进行,对系统日志eventLog进行遍历,找出上个月和这个月ID为6005和 6006的事件,然后输出每一次的开机时间和关机时间,以及每一次开关机的运行时间。接下来统计每一天的运行的总时间,首先要确定每个开机事件是否在同一 天,如果是在同一天,那么那一天的运行时间就要再在原来的基础上加上这一次的运行时间;如果不是同一天,那么就证明上一次的记录是第一天的记录,而这一次 的记录是第二天的记录,所以上一次的记录就是第一天的结尾,于是第一天的总运行时间就可以确定了,输出第一天的运行总时间。……以此类推,一直遍历到最后 一天也就是今天的运行时间,今天的运行时间等于本次的机器运行时间DateTime.Now-start加上今天其他几次的运行时间,计算完成后就可以输出今天的运行时间。而上个月每天的运行总时间取和就等于上个月总的运行时间,最后使用TotalHours函数将Timespan转换为小时数输出。
/// <summary>
/// 清理所有正在使用的资源。
/// </summary>
protected override void Dispose( bool disposing )
{
if( disposing )
{
if (components != null)
{
components.Dispose();
}
}
base.Dispose( disposing );
}
//下面的代码都是跟界面设计有关的,可以不必理会。
#region Windows 窗体设计器生成的代码
/// <summary>
/// 设计器支持所需的方法- 不要使用代码编辑器修改
/// 此方法的内容。
/// </summary>
private void InitializeComponent()
{
this.components = new System.ComponentModel.Container();
System.Resources.ResourceManager resources = new System.Resources.ResourceManager(typeof(MainForm));
this.evLog = new System.Diagnostics.EventLog();
this.listView = new System.Windows.Forms.ListView();
this.ch_StartTime = new System.Windows.Forms.ColumnHeader();
this.ch_PowerOffTime = new System.Windows.Forms.ColumnHeader();
this.ch_RunningTime = new System.Windows.Forms.ColumnHeader();
this.contextMenu = new System.Windows.Forms.ContextMenu();
this.menuItem_ExportDetail = new System.Windows.Forms.MenuItem();
this.menuItem_ExportDays = new System.Windows.Forms.MenuItem();
this.menuItem_About = new System.Windows.Forms.MenuItem();
this.toolTip = new System.Windows.Forms.ToolTip(this.components);
((System.ComponentModel.ISupportInitialize)(this.evLog)).BeginInit();
this.SuspendLayout();
//
// evLog
//
this.evLog.Log = "System";
this.evLog.SynchronizingObject = this;
//
// listView
//
this.listView.AccessibleDescription = resources.GetString("listView.AccessibleDescription");
this.listView.AccessibleName = resources.GetString("listView.AccessibleName");
this.listView.Alignment = ((System.Windows.Forms.ListViewAlignment)(resources.GetObject("listView.Alignment")));
this.listView.Anchor = ((System.Windows.Forms.AnchorStyles)(resources.GetObject("listView.Anchor")));
this.listView.BackgroundImage = ((System.Drawing.Image)(resources.GetObject("listView.BackgroundImage")));
this.listView.BorderStyle = System.Windows.Forms.BorderStyle.None;
this.listView.CausesValidation = false;
this.listView.Columns.AddRange(new System.Windows.Forms.ColumnHeader[] {
this.ch_StartTime,
this.ch_PowerOffTime,
this.ch_RunningTime});
this.listView.ContextMenu = this.contextMenu;
this.listView.Dock = ((System.Windows.Forms.DockStyle)(resources.GetObject("listView.Dock")));
this.listView.Enabled = ((bool)(resources.GetObject("listView.Enabled")));
this.listView.Font = ((System.Drawing.Font)(resources.GetObject("listView.Font")));
this.listView.FullRowSelect = true;
this.listView.GridLines = true;
this.listView.HeaderStyle = System.Windows.Forms.ColumnHeaderStyle.Nonclickable;
this.listView.ImeMode = ((System.Windows.Forms.ImeMode)(resources.GetObject("listView.ImeMode")));
this.listView.LabelWrap = ((bool)(resources.GetObject("listView.LabelWrap")));
this.listView.Location = ((System.Drawing.Point)(resources.GetObject("listView.Location")));
this.listView.Name = "listView";
this.listView.RightToLeft = ((System.Windows.Forms.RightToLeft)(resources.GetObject("listView.RightToLeft")));
this.listView.Size = ((System.Drawing.Size)(resources.GetObject("listView.Size")));
this.listView.TabIndex = ((int)(resources.GetObject("listView.TabIndex")));
this.listView.Text = resources.GetString("listView.Text");
this.toolTip.SetToolTip(this.listView, resources.GetString("listView.ToolTip"));
this.listView.View = System.Windows.Forms.View.Details;
this.listView.Visible = ((bool)(resources.GetObject("listView.Visible")));
//
// ch_StartTime
//
this.ch_StartTime.Text = resources.GetString("ch_StartTime.Text");
this.ch_StartTime.TextAlign = ((System.Windows.Forms.HorizontalAlignment)(resources.GetObject("ch_StartTime.TextAlign")));
this.ch_StartTime.Width = ((int)(resources.GetObject("ch_StartTime.Width")));
//
// ch_PowerOffTime
//
this.ch_PowerOffTime.Text = resources.GetString("ch_PowerOffTime.Text");
this.ch_PowerOffTime.TextAlign = ((System.Windows.Forms.HorizontalAlignment)(resources.GetObject("ch_PowerOffTime.TextAlign")));
this.ch_PowerOffTime.Width = ((int)(resources.GetObject("ch_PowerOffTime.Width")));
//
// ch_RunningTime
//
this.ch_RunningTime.Text = resources.GetString("ch_RunningTime.Text");
this.ch_RunningTime.TextAlign = ((System.Windows.Forms.HorizontalAlignment)(resources.GetObject("ch_RunningTime.TextAlign")));
this.ch_RunningTime.Width = ((int)(resources.GetObject("ch_RunningTime.Width")));
//
// contextMenu
//
this.contextMenu.MenuItems.AddRange(new System.Windows.Forms.MenuItem[] {
this.menuItem_ExportDetail,
this.menuItem_ExportDays,
this.menuItem_About});
this.contextMenu.RightToLeft = ((System.Windows.Forms.RightToLeft)(resources.GetObject("contextMenu.RightToLeft")));
//
// menuItem_ExportDetail
//
this.menuItem_ExportDetail.Enabled = ((bool)(resources.GetObject("menuItem_ExportDetail.Enabled")));
this.menuItem_ExportDetail.Index = 0;
this.menuItem_ExportDetail.Shortcut = ((System.Windows.Forms.Shortcut)(resources.GetObject("menuItem_ExportDetail.Shortcut")));
this.menuItem_ExportDetail.ShowShortcut = ((bool)(resources.GetObject("menuItem_ExportDetail.ShowShortcut")));
this.menuItem_ExportDetail.Text = resources.GetString("menuItem_ExportDetail.Text");
this.menuItem_ExportDetail.Visible = ((bool)(resources.GetObject("menuItem_ExportDetail.Visible")));
this.menuItem_ExportDetail.Click += new System.EventHandler(this.menuItem_ExportDetail_Click);
//
// menuItem_ExportDays
//
this.menuItem_ExportDays.Enabled = ((bool)(resources.GetObject("menuItem_ExportDays.Enabled")));
this.menuItem_ExportDays.Index = 1;
this.menuItem_ExportDays.Shortcut = ((System.Windows.Forms.Shortcut)(resources.GetObject("menuItem_ExportDays.Shortcut")));
this.menuItem_ExportDays.ShowShortcut = ((bool)(resources.GetObject("menuItem_ExportDays.ShowShortcut")));
this.menuItem_ExportDays.Text = resources.GetString("menuItem_ExportDays.Text");
this.menuItem_ExportDays.Visible = ((bool)(resources.GetObject("menuItem_ExportDays.Visible")));
this.menuItem_ExportDays.Click += new System.EventHandler(this.menuItem_ExportDays_Click);
//
// menuItem_About
//
this.menuItem_About.Enabled = ((bool)(resources.GetObject("menuItem_About.Enabled")));
this.menuItem_About.Index = 2;
this.menuItem_About.Shortcut = ((System.Windows.Forms.Shortcut)(resources.GetObject("menuItem_About.Shortcut")));
this.menuItem_About.ShowShortcut = ((bool)(resources.GetObject("menuItem_About.ShowShortcut")));
this.menuItem_About.Text = resources.GetString("menuItem_About.Text");
this.menuItem_About.Visible = ((bool)(resources.GetObject("menuItem_About.Visible")));
this.menuItem_About.Click += new System.EventHandler(this.menuItem_About_Click);
//
// toolTip
//
this.toolTip.AutomaticDelay = 200;
//
// MainForm
//
this.AccessibleDescription = resources.GetString("$this.AccessibleDescription");
this.AccessibleName = resources.GetString("$this.AccessibleName");
this.AutoScaleBaseSize = ((System.Drawing.Size)(resources.GetObject("$this.AutoScaleBaseSize")));
this.AutoScroll = ((bool)(resources.GetObject("$this.AutoScroll")));
this.AutoScrollMargin = ((System.Drawing.Size)(resources.GetObject("$this.AutoScrollMargin")));
this.AutoScrollMinSize = ((System.Drawing.Size)(resources.GetObject("$this.AutoScrollMinSize")));
this.BackgroundImage = ((System.Drawing.Image)(resources.GetObject("$this.BackgroundImage")));
this.ClientSize = ((System.Drawing.Size)(resources.GetObject("$this.ClientSize")));
this.Controls.Add(this.listView);
this.Enabled = ((bool)(resources.GetObject("$this.Enabled")));
this.Font = ((System.Drawing.Font)(resources.GetObject("$this.Font")));
this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon")));
this.ImeMode = ((System.Windows.Forms.ImeMode)(resources.GetObject("$this.ImeMode")));
this.Location = ((System.Drawing.Point)(resources.GetObject("$this.Location")));
this.MaximumSize = ((System.Drawing.Size)(resources.GetObject("$this.MaximumSize")));
this.MinimumSize = ((System.Drawing.Size)(resources.GetObject("$this.MinimumSize")));
this.Name = "MainForm";
this.RightToLeft = ((System.Windows.Forms.RightToLeft)(resources.GetObject("$this.RightToLeft")));
this.StartPosition = ((System.Windows.Forms.FormStartPosition)(resources.GetObject("$this.StartPosition")));
this.Text = resources.GetString("$this.Text");
this.toolTip.SetToolTip(this, resources.GetString("$this.ToolTip"));
((System.ComponentModel.ISupportInitialize)(this.evLog)).EndInit();
this.ResumeLayout(false);
}
#endregion
/// <summary>
/// 应用程序的主入口点。
/// </summary>
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.Run(new MainForm());
}
private void menuItem_About_Click(object sender, System.EventArgs e)
{
MessageBox.Show(LocRM.GetString("AboutMessage"),LocRM.GetString("AboutTitle")
, MessageBoxButtons.OK, MessageBoxIcon.Information);
}
//下面这些功能是跟两个菜单项有关的,实现数据复制到剪贴板
private void menuItem_ExportDetail_Click(object sender, System.EventArgs e)
{
DataExport(false);
}
private void menuItem_ExportDays_Click(object sender, System.EventArgs e)
{
DataExport(true);
}
private void DataExport(bool inDays)
{
DataObject data = new DataObject();
StringWriter sw = new StringWriter();
foreach(ListViewItem lvi in listView.Items)
{
if(inDays == true)
{
if(lvi.SubItems[1].Text == LocRM.GetString("Running Time:"))
{
sw.Write(lvi.SubItems[0].Text);
sw.Write("/t");
sw.Write(lvi.SubItems[1].Text);
sw.Write("/t");
sw.Write(lvi.SubItems[2].Text);
sw.WriteLine();
}
}
else
{
if(lvi.SubItems[1].Text != LocRM.GetString("Running Time:"))
{
sw.Write(lvi.SubItems[0].Text);
sw.Write("/t");
sw.Write(lvi.SubItems[1].Text);
sw.Write("/t");
sw.Write(lvi.SubItems[2].Text);
sw.WriteLine();
}
}
}
sw.Close();
data.SetData(sw.ToString());
Clipboard.SetDataObject(data, true); //这个是实现复制数据到剪贴板
}
}
}
namespace PC_PowerOn_Time
{
/// <summary>
/// MainForm 的摘要说明。
/// </summary>
public class MainForm : System.Windows.Forms.Form //界面生成后执行下面的代码
{
internal System.Diagnostics.EventLog evLog; //导入系统时间日志
private System.Windows.Forms.ListView listView; //表格
private System.Windows.Forms.ColumnHeader ch_StartTime; //“开机时间”表格项
private System.Windows.Forms.ColumnHeader ch_PowerOffTime;//“关机时间”表格项
private System.Windows.Forms.ColumnHeader ch_RunningTime;//“运行时间”表格项
private System.Windows.Forms.MenuItem menuItem_About; //菜单
private System.Windows.Forms.ContextMenu contextMenu; //菜单
System.Resources.ResourceManager LocRM = new /*定义一个资源管理器*/
System.Resources.ResourceManager("PC_PowerOn_Time.InCodeStrings",typeof(MainForm).Assembly);
private System.Windows.Forms.MenuItem menuItem_ExportDetail; //定义一个菜单项
private System.Windows.Forms.MenuItem menuItem_ExportDays; //定义一个菜单项
private System.Windows.Forms.ToolTip toolTip; //定义工具提示
private System.ComponentModel.IContainer components;
//小结:上面四句都是跟程序右键弹出的菜单有关,可以不必理会。
public MainForm() //开始设计这个窗口
{
//
// Windows 窗体设计器支持所必需的
//
InitializeComponent(); //初始化组件
DateTime start = new DateTime(), stop = new DateTime(), prev_start = new DateTime();//定义开机时间、关机时间为DataTime类型,还有一个prev_start记录上一个记录的时间,三个的初始值都是当前时 间
TimeSpan dayOnTime = new TimeSpan(); //这个就是每天的总运行时间!!!
TimeSpan totaltime =new TimeSpan(); //记录这个月的总运行时间
foreach (System.Diagnostics.EventLogEntry ele in evLog.Entries) //foreach根据字面含义应该是一个遍历函数,对Eventlog时间日志里的每一项进行遍历,找出ID=6005和6006的项,6005对应开 机时间,6006对应关机时间
{
if(ele.Source == "EventLog") //当遍历的项是EventLog里面的项的时候,这个我觉得效率很低,因为它对整个事件日志都作了遍历,而我们要找的只是系统事件日志,不知道以后能不 能直接限定就在EventLog里面查找,而不是用if来判断
{
if(ele.EventID == 6005) // 开机服务
{
prev_start=start; //把start的值赋给它,也就是上一个记录的时间
start = ele.TimeGenerated; //获取与这个事件对应的时间,即开机时间
}
if(ele.EventID == 6006) // 关机服务
{
stop = ele.TimeGenerated; //获取与这个事件对应的时间,即关机时间
//下面要计算一天的总运行时间,应该先判断上个记录和这个记录是不是在同一天,以决定是要在上个记录的基础上加这一次的时间还是直接等于这个记录所对应的时间
if(prev_start.Day != start.Day && prev_start.Year != 1 &&start.Month==DateTime.Now.Month-1)
//先计算上一个月的运行时间。如果不是同一天,这一天的运行时间直接等于这个记录所对应的运行时间。而上一个记录就是这个记录前一天的最后一次执行机器的记录。所以我们可以先对前一天的总时间进行计算。执行以下语句
{
ListViewItem lviSub = new ListViewItem(); //声明一行表格
//先写前一天的机器总开机时间
lviSub.BackColor = Color.AliceBlue; //表格底色设置为浅蓝色,以突出总时间(很浅,不仔细看以为是白色)
//先记录前一天对应的年、月、日以及星期几
lviSub.SubItems[0].Text = prev_start.ToString(Application.CurrentCulture.DateTimeFormat.LongDatePattern)
+ "/t" + prev_start.DayOfWeek.ToString(Application.CurrentCulture);
lviSub.SubItems[0].Font = new Font(lviSub.SubItems[0].Font, FontStyle.Bold);
lviSub.SubItems.Add(LocRM.GetString("Running Time:")); //在第二栏添加“运行时间”字样
totaltime += dayOnTime; //计算一个月总运行时间
lviSub.SubItems.Add(dayOnTime.ToString()); //添加日期
dayOnTime = stop-start; //计算那一天的运行时间
listView.Items.Add(lviSub); //添加这一行的数据进入表格
}
//计算这个月的运行时间,代码和上面的类似,只是不需要计算一个月的总运行时间,所以没有totaltime += dayOnTime;这一句
else if (prev_start.Day != start.Day && prev_start.Year != 1 && start.Month == DateTime.Now.Month)
{
ListViewItem lviSub = new ListViewItem();
lviSub.BackColor = Color.AliceBlue;
lviSub.SubItems[0].Text = prev_start.ToString(Application.CurrentCulture.DateTimeFormat.LongDatePattern)
+ "/t" + prev_start.DayOfWeek.ToString(Application.CurrentCulture);
lviSub.SubItems[0].Font = new Font(lviSub.SubItems[0].Font, FontStyle.Bold);
lviSub.SubItems.Add(LocRM.GetString("Running Time:"));
lviSub.SubItems.Add(dayOnTime.ToString());
dayOnTime = stop - start;
listView.Items.Add(lviSub);
}
//如果是在同一天,那么这个记录所对应的那一天的运行时间就等于上一个记录的运行时间加上这个记录的运行时间(可能还会继续加下一个记录,如果下一个记录和这个记录同一天),即dayOnTime=dayOnTime+(stop-start);
else
{
dayOnTime += stop-start; //这个记录对应的那一天的运行时间(可能还会继续加)
}
//接下来我们要添加每一次开机和关机对应的时间以及运行的时间
ListViewItem lvi = new ListViewItem(); //声明一个表单项lvi
lvi.SubItems[0].Text = start.ToString("F"); //在lvi中添加开机时间
lvi.SubItems.Add( stop.ToString("F") ); //在lvi中添加关机时间
lvi.SubItems.Add((stop - start).ToString() ); //在lvi中添加运行时间
listView.Items.Add(lvi); //把lvi里的数据添加数据进表格
}
}
}
//小结:从上面我们可以获得几个比较有用的数据,某一个记录对应的年,月,日和星期分别为:.Year,.Month,.Day,DayOfWeek
//有了这几个数据我们接下来进行统计的时候就方便多了。
//遍历完后只剩下今天还没有计算出来了,我们要计算今天的运行时间,今天的运行时间比较特殊,因为我们现在没有关机,也就是少一个ID6006的事件。今天的运行时间就等于当前的时间减去开机时间,如果今天还运行过几次机器,那么就要再加上前几次运行的时间。
if(prev_start.Day != start.Day && prev_start.Year != 1)
{
ListViewItem lviSub = new ListViewItem(); //先把昨天的运行时间添加进表单
lviSub.BackColor = Color.AliceBlue;
lviSub.SubItems[0].Text = prev_start.ToString(Application.CurrentCulture.DateTimeFormat.LongDatePattern)
+ " " + prev_start.DayOfWeek.ToString(Application.CurrentCulture);
lviSub.SubItems[0].Font = new Font(lviSub.SubItems[0].Font, FontStyle.Bold);
lviSub.SubItems.Add(LocRM.GetString("Running Time:"));
lviSub.SubItems.Add(dayOnTime.ToString()); //到这里昨天的一切数据都已经放进了表单项,就等放入表单
dayOnTime = DateTime.Now-start; //这个就是我们本次开机到现在的运行时间
listView.Items.Add(lviSub); //把表单项放入表单
}
else
{
dayOnTime += DateTime.Now-start; //计算今天的总运行时间
}
//下面就是计算今天的运行时间了
listView.Items.Add(new ListViewItem(new string[] { start.ToString("F"),
DateTime.Now.ToString("F"),
(DateTime.Now-start).ToString().Substring(0, 8), })); //依然是增加一行表单
ListViewItem lviTodaySub = new ListViewItem(); //声明一个表单项
lviTodaySub.BackColor = Color.LightBlue; //底色设成浅蓝(这个浅蓝颜色比较清楚,强调是今天)
lviTodaySub.SubItems[0].Text = start.ToString(Application.CurrentCulture.DateTimeFormat.LongDatePattern)
+ "/t" + start.DayOfWeek.ToString(Application.CurrentCulture); //添加年月日和星期
lviTodaySub.SubItems[0].Font = new Font(lviTodaySub.SubItems[0].Font, FontStyle.Bold); //设置字体
lviTodaySub.SubItems.Add(LocRM.GetString("Running Time:")); //添加“运行时间”字样
lviTodaySub.SubItems.Add(dayOnTime.ToString().Substring(0, 8)); //添加这一天的运行时间
listView.Items.Add(lviTodaySub); //把这一行表单项添加进表单里面
//下面输出上一个月份的运行时间
int lastmonth = DateTime.Now.Month - 1; //记录上个月的数字
//MessageBox.Show(lastmonth.ToString()+"月 日~"+last.Day.ToString()+"日总运行时间为:" + totaltime.TotalHours.ToString()+"个小时"); //是否弹出一个对话框输出结果,取消注释就会另外弹出对话框输出结果
ListViewItem lresult = new ListViewItem();
lresult.BackColor = Color.Green;
lresult.SubItems[0].Text = lastmonth.ToString()+"月日~"+last.Day.ToString()+"日" ;
lresult.SubItems[0].Font = new Font(lviTodaySub.SubItems[0].Font, FontStyle.Bold);
lresult.SubItems[0].ForeColor=Color.White;
lresult.SubItems.Add("月总运行时间:");
lresult.SubItems.Add(totaltime.TotalHours.ToString()+"个小时"); //TotalHours的作用是将Timespan转换为小时数
listView.Items.Add(lresult);
}
//总结:利用系统日志完成计算主要是以遍历的形式进行,对系统日志eventLog进行遍历,找出上个月和这个月ID为6005和 6006的事件,然后输出每一次的开机时间和关机时间,以及每一次开关机的运行时间。接下来统计每一天的运行的总时间,首先要确定每个开机事件是否在同一 天,如果是在同一天,那么那一天的运行时间就要再在原来的基础上加上这一次的运行时间;如果不是同一天,那么就证明上一次的记录是第一天的记录,而这一次 的记录是第二天的记录,所以上一次的记录就是第一天的结尾,于是第一天的总运行时间就可以确定了,输出第一天的运行总时间。……以此类推,一直遍历到最后 一天也就是今天的运行时间,今天的运行时间等于本次的机器运行时间DateTime.Now-start加上今天其他几次的运行时间,计算完成后就可以输出今天的运行时间。而上个月每天的运行总时间取和就等于上个月总的运行时间,最后使用TotalHours函数将Timespan转换为小时数输出。
/// <summary>
/// 清理所有正在使用的资源。
/// </summary>
protected override void Dispose( bool disposing )
{
if( disposing )
{
if (components != null)
{
components.Dispose();
}
}
base.Dispose( disposing );
}
//下面的代码都是跟界面设计有关的,可以不必理会。
#region Windows 窗体设计器生成的代码
/// <summary>
/// 设计器支持所需的方法- 不要使用代码编辑器修改
/// 此方法的内容。
/// </summary>
private void InitializeComponent()
{
this.components = new System.ComponentModel.Container();
System.Resources.ResourceManager resources = new System.Resources.ResourceManager(typeof(MainForm));
this.evLog = new System.Diagnostics.EventLog();
this.listView = new System.Windows.Forms.ListView();
this.ch_StartTime = new System.Windows.Forms.ColumnHeader();
this.ch_PowerOffTime = new System.Windows.Forms.ColumnHeader();
this.ch_RunningTime = new System.Windows.Forms.ColumnHeader();
this.contextMenu = new System.Windows.Forms.ContextMenu();
this.menuItem_ExportDetail = new System.Windows.Forms.MenuItem();
this.menuItem_ExportDays = new System.Windows.Forms.MenuItem();
this.menuItem_About = new System.Windows.Forms.MenuItem();
this.toolTip = new System.Windows.Forms.ToolTip(this.components);
((System.ComponentModel.ISupportInitialize)(this.evLog)).BeginInit();
this.SuspendLayout();
//
// evLog
//
this.evLog.Log = "System";
this.evLog.SynchronizingObject = this;
//
// listView
//
this.listView.AccessibleDescription = resources.GetString("listView.AccessibleDescription");
this.listView.AccessibleName = resources.GetString("listView.AccessibleName");
this.listView.Alignment = ((System.Windows.Forms.ListViewAlignment)(resources.GetObject("listView.Alignment")));
this.listView.Anchor = ((System.Windows.Forms.AnchorStyles)(resources.GetObject("listView.Anchor")));
this.listView.BackgroundImage = ((System.Drawing.Image)(resources.GetObject("listView.BackgroundImage")));
this.listView.BorderStyle = System.Windows.Forms.BorderStyle.None;
this.listView.CausesValidation = false;
this.listView.Columns.AddRange(new System.Windows.Forms.ColumnHeader[] {
this.ch_StartTime,
this.ch_PowerOffTime,
this.ch_RunningTime});
this.listView.ContextMenu = this.contextMenu;
this.listView.Dock = ((System.Windows.Forms.DockStyle)(resources.GetObject("listView.Dock")));
this.listView.Enabled = ((bool)(resources.GetObject("listView.Enabled")));
this.listView.Font = ((System.Drawing.Font)(resources.GetObject("listView.Font")));
this.listView.FullRowSelect = true;
this.listView.GridLines = true;
this.listView.HeaderStyle = System.Windows.Forms.ColumnHeaderStyle.Nonclickable;
this.listView.ImeMode = ((System.Windows.Forms.ImeMode)(resources.GetObject("listView.ImeMode")));
this.listView.LabelWrap = ((bool)(resources.GetObject("listView.LabelWrap")));
this.listView.Location = ((System.Drawing.Point)(resources.GetObject("listView.Location")));
this.listView.Name = "listView";
this.listView.RightToLeft = ((System.Windows.Forms.RightToLeft)(resources.GetObject("listView.RightToLeft")));
this.listView.Size = ((System.Drawing.Size)(resources.GetObject("listView.Size")));
this.listView.TabIndex = ((int)(resources.GetObject("listView.TabIndex")));
this.listView.Text = resources.GetString("listView.Text");
this.toolTip.SetToolTip(this.listView, resources.GetString("listView.ToolTip"));
this.listView.View = System.Windows.Forms.View.Details;
this.listView.Visible = ((bool)(resources.GetObject("listView.Visible")));
//
// ch_StartTime
//
this.ch_StartTime.Text = resources.GetString("ch_StartTime.Text");
this.ch_StartTime.TextAlign = ((System.Windows.Forms.HorizontalAlignment)(resources.GetObject("ch_StartTime.TextAlign")));
this.ch_StartTime.Width = ((int)(resources.GetObject("ch_StartTime.Width")));
//
// ch_PowerOffTime
//
this.ch_PowerOffTime.Text = resources.GetString("ch_PowerOffTime.Text");
this.ch_PowerOffTime.TextAlign = ((System.Windows.Forms.HorizontalAlignment)(resources.GetObject("ch_PowerOffTime.TextAlign")));
this.ch_PowerOffTime.Width = ((int)(resources.GetObject("ch_PowerOffTime.Width")));
//
// ch_RunningTime
//
this.ch_RunningTime.Text = resources.GetString("ch_RunningTime.Text");
this.ch_RunningTime.TextAlign = ((System.Windows.Forms.HorizontalAlignment)(resources.GetObject("ch_RunningTime.TextAlign")));
this.ch_RunningTime.Width = ((int)(resources.GetObject("ch_RunningTime.Width")));
//
// contextMenu
//
this.contextMenu.MenuItems.AddRange(new System.Windows.Forms.MenuItem[] {
this.menuItem_ExportDetail,
this.menuItem_ExportDays,
this.menuItem_About});
this.contextMenu.RightToLeft = ((System.Windows.Forms.RightToLeft)(resources.GetObject("contextMenu.RightToLeft")));
//
// menuItem_ExportDetail
//
this.menuItem_ExportDetail.Enabled = ((bool)(resources.GetObject("menuItem_ExportDetail.Enabled")));
this.menuItem_ExportDetail.Index = 0;
this.menuItem_ExportDetail.Shortcut = ((System.Windows.Forms.Shortcut)(resources.GetObject("menuItem_ExportDetail.Shortcut")));
this.menuItem_ExportDetail.ShowShortcut = ((bool)(resources.GetObject("menuItem_ExportDetail.ShowShortcut")));
this.menuItem_ExportDetail.Text = resources.GetString("menuItem_ExportDetail.Text");
this.menuItem_ExportDetail.Visible = ((bool)(resources.GetObject("menuItem_ExportDetail.Visible")));
this.menuItem_ExportDetail.Click += new System.EventHandler(this.menuItem_ExportDetail_Click);
//
// menuItem_ExportDays
//
this.menuItem_ExportDays.Enabled = ((bool)(resources.GetObject("menuItem_ExportDays.Enabled")));
this.menuItem_ExportDays.Index = 1;
this.menuItem_ExportDays.Shortcut = ((System.Windows.Forms.Shortcut)(resources.GetObject("menuItem_ExportDays.Shortcut")));
this.menuItem_ExportDays.ShowShortcut = ((bool)(resources.GetObject("menuItem_ExportDays.ShowShortcut")));
this.menuItem_ExportDays.Text = resources.GetString("menuItem_ExportDays.Text");
this.menuItem_ExportDays.Visible = ((bool)(resources.GetObject("menuItem_ExportDays.Visible")));
this.menuItem_ExportDays.Click += new System.EventHandler(this.menuItem_ExportDays_Click);
//
// menuItem_About
//
this.menuItem_About.Enabled = ((bool)(resources.GetObject("menuItem_About.Enabled")));
this.menuItem_About.Index = 2;
this.menuItem_About.Shortcut = ((System.Windows.Forms.Shortcut)(resources.GetObject("menuItem_About.Shortcut")));
this.menuItem_About.ShowShortcut = ((bool)(resources.GetObject("menuItem_About.ShowShortcut")));
this.menuItem_About.Text = resources.GetString("menuItem_About.Text");
this.menuItem_About.Visible = ((bool)(resources.GetObject("menuItem_About.Visible")));
this.menuItem_About.Click += new System.EventHandler(this.menuItem_About_Click);
//
// toolTip
//
this.toolTip.AutomaticDelay = 200;
//
// MainForm
//
this.AccessibleDescription = resources.GetString("$this.AccessibleDescription");
this.AccessibleName = resources.GetString("$this.AccessibleName");
this.AutoScaleBaseSize = ((System.Drawing.Size)(resources.GetObject("$this.AutoScaleBaseSize")));
this.AutoScroll = ((bool)(resources.GetObject("$this.AutoScroll")));
this.AutoScrollMargin = ((System.Drawing.Size)(resources.GetObject("$this.AutoScrollMargin")));
this.AutoScrollMinSize = ((System.Drawing.Size)(resources.GetObject("$this.AutoScrollMinSize")));
this.BackgroundImage = ((System.Drawing.Image)(resources.GetObject("$this.BackgroundImage")));
this.ClientSize = ((System.Drawing.Size)(resources.GetObject("$this.ClientSize")));
this.Controls.Add(this.listView);
this.Enabled = ((bool)(resources.GetObject("$this.Enabled")));
this.Font = ((System.Drawing.Font)(resources.GetObject("$this.Font")));
this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon")));
this.ImeMode = ((System.Windows.Forms.ImeMode)(resources.GetObject("$this.ImeMode")));
this.Location = ((System.Drawing.Point)(resources.GetObject("$this.Location")));
this.MaximumSize = ((System.Drawing.Size)(resources.GetObject("$this.MaximumSize")));
this.MinimumSize = ((System.Drawing.Size)(resources.GetObject("$this.MinimumSize")));
this.Name = "MainForm";
this.RightToLeft = ((System.Windows.Forms.RightToLeft)(resources.GetObject("$this.RightToLeft")));
this.StartPosition = ((System.Windows.Forms.FormStartPosition)(resources.GetObject("$this.StartPosition")));
this.Text = resources.GetString("$this.Text");
this.toolTip.SetToolTip(this, resources.GetString("$this.ToolTip"));
((System.ComponentModel.ISupportInitialize)(this.evLog)).EndInit();
this.ResumeLayout(false);
}
#endregion
/// <summary>
/// 应用程序的主入口点。
/// </summary>
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.Run(new MainForm());
}
private void menuItem_About_Click(object sender, System.EventArgs e)
{
MessageBox.Show(LocRM.GetString("AboutMessage"),LocRM.GetString("AboutTitle")
, MessageBoxButtons.OK, MessageBoxIcon.Information);
}
//下面这些功能是跟两个菜单项有关的,实现数据复制到剪贴板
private void menuItem_ExportDetail_Click(object sender, System.EventArgs e)
{
DataExport(false);
}
private void menuItem_ExportDays_Click(object sender, System.EventArgs e)
{
DataExport(true);
}
private void DataExport(bool inDays)
{
DataObject data = new DataObject();
StringWriter sw = new StringWriter();
foreach(ListViewItem lvi in listView.Items)
{
if(inDays == true)
{
if(lvi.SubItems[1].Text == LocRM.GetString("Running Time:"))
{
sw.Write(lvi.SubItems[0].Text);
sw.Write("/t");
sw.Write(lvi.SubItems[1].Text);
sw.Write("/t");
sw.Write(lvi.SubItems[2].Text);
sw.WriteLine();
}
}
else
{
if(lvi.SubItems[1].Text != LocRM.GetString("Running Time:"))
{
sw.Write(lvi.SubItems[0].Text);
sw.Write("/t");
sw.Write(lvi.SubItems[1].Text);
sw.Write("/t");
sw.Write(lvi.SubItems[2].Text);
sw.WriteLine();
}
}
}
sw.Close();
data.SetData(sw.ToString());
Clipboard.SetDataObject(data, true); //这个是实现复制数据到剪贴板
}
}
}