实现效果:

知识运用:
Eventlog类的SourceExists方法 //确定指定的事件源是否已在本地计算机注册
public static bool SourceExists(string source)
和DeleteEventSource方法 //从事件日志中移除应用程序的事件源注册
public static void DeleteEventLogSource(string source)
实现代码:
private void Form1_Load(object sender, EventArgs e)
{
if (System.Diagnostics.EventLog.SourceExists("MySource")) //判断是否存在事件源
{
System.Diagnostics.EventLog.DeleteEventSource("MySource"); //删除事件源
}
System.Diagnostics.EventLog.CreateEventSource("MySource","NewLog1"); //创建日志信息
eventLog1.Log = "NewLog1"; //设置日志名称
eventLog1.Source = "MySource"; //事件源名称
eventLog1.MachineName = "."; //表是本机
}
private void btn_write_Click(object sender, EventArgs e)
{
if (System.Diagnostics.EventLog.Exists("NewLog1")) //判断日志文件是否存在
{
if (textBox1.Text != "") //文本框不为空
{
eventLog1.WriteEntry(textBox1.Text.ToString()); //写入日志
MessageBox.Show("日志信息写入成功"); //消息框提醒
textBox1.Text = ""; //清除文本框内容
}
else { MessageBox.Show("日志内容不能为空"); }
}
else
{
MessageBox.Show("日志信息不存在");
}
}
浙公网安备 33010602011771号