zl程序教程

您现在的位置是:首页 >  工具

当前栏目

使用EventLog组件向本机现有日志中添加条目

组件日志 添加 现有 本机 条目 使用
2023-09-14 09:00:20 时间

实现效果:

  

知识运用:

  EventLog组件的MachineName属性  //获取或设置在其上读取或写入事件的计算机名称

  public string MachineName  {get;set; }

  和WriteEntry方法      //将信息类型和给定的消息文本一起写入事件日志

  public void WriteEntry(string message)

实现代码:

        private void Form1_Load(object sender, EventArgs e)
        {
            if (eventLog1.Entries.Count > 0)
            {
                foreach(System.Diagnostics.EventLogEntry evn in eventLog1.Entries )     //遍历所有日志
                {
                    if (comboBox1.Items.Count == 0)                                     //没有ComboBox项
                    {
                        comboBox1.Items.Add(evn.Source.ToString());                     //添加日志信息
                    }
                    else 
                    {
                        if (!(comboBox1.Items.Contains(evn.Source.ToString())))         //判断是否重复
                            comboBox1.Items.Add(evn.Source.ToString());                 //添加日志信息
                    }
                }
            }
        }

        private void button1_Click(object sender, EventArgs e)
        {
            if (comboBox1.SelectedItem==null)                                           //如果没有选择项
            {
                MessageBox.Show("请选择一项");
                return;
            }
            if (textBox1.Text == "")                                                    //如果没有填写日志内容
            {           
                MessageBox.Show("请输入要添加的内容");
                textBox1.Focus();                                                       //控件的到焦点
                return;                                                                 //退出方法
            }
            eventLog1.Log = "System";                                                   //设置读写日志的名称
            eventLog1.Source = textBox1.Text.ToString();                                //设置日志源
            eventLog1.MachineName = ".";                                                //设置写入日志的计算机名称
            eventLog1.WriteEntry(textBox1.Text.ToString());
            MessageBox.Show("添加成功");               
            listView1.Items.Clear();
            if (eventLog1.Entries.Count > 0)                                             //如果日志中有内容
            {
                foreach (System.Diagnostics.EventLogEntry evn in eventLog1.Entries)      //遍历日志内容
                {
                    listView1.Items.Add(evn.Message);                                    //在控件中显示日志内容
                }
            }
        }