實現效果:

知識運用:
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("日志信息不存在");
}
}
