您的位置:首页 > 编程语言 > C#

C# 利用WMI进行日志监视

2007-10-03 11:10 447 查看
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Management;
using System.Windows.Forms;

namespace MonitorLogEvent
{
    public partial class frmMain : Form
    {
        public frmMain()
        {
            InitializeComponent();
        }

        private ManagementEventWatcher LogEvent=null;

        private void cmdStart_Click(object sender, EventArgs e)
        {
            ConnectionOptions co = new ConnectionOptions();
            co.Impersonation = ImpersonationLevel.Impersonate;
            co.EnablePrivileges = true;
            ManagementScope scope = new ManagementScope("////.//root//cimv2", co);
            WqlEventQuery wql = new WqlEventQuery("__InstanceCreationEvent", new TimeSpan(0, 0, 1), "TargetInstance ISA 'Win32_NTLogEvent'");
            LogEvent = new ManagementEventWatcher(scope, wql);
            LogEvent.EventArrived += new EventArrivedEventHandler(LogEvent_EventArrived);
            LogEvent.Start();
        }

        private void LogEvent_EventArrived(object sender,EventArrivedEventArgs e)
        {
            ManagementBaseObject mo = (ManagementBaseObject)e.NewEvent.Properties["TargetInstance"].Value;
            PropertyDataCollection  propertyDataCollections= mo.Properties;
            foreach (PropertyData data in propertyDataCollections)
            {
                MessageBox.Show(data.Name);
            }

                //Category
                //CategoryString
                //ComputerName
                //Data
                //EventCode
                //EventIdentifier
                //EventType
                //InsertionStrings
                //Logfile
                //Message
                //RecordNumber
                //SourceName
                //TimeFGenerated
                //TimeWritten
                //Type
                //User
        }

        private void frmMain_Load(object sender, EventArgs e)
        {
            this.FormClosing += new FormClosingEventHandler(frmMain_FormClosing);
        }

        private void frmMain_FormClosing(object sender, EventArgs e)
        {
            if (LogEvent != null)
            {
                LogEvent.Stop();
                LogEvent = null;
            }

        }

        private void cmdEnd_Click(object sender, EventArgs e)
        {
            if (LogEvent!=null)
            {
                LogEvent.Stop();
                LogEvent = null;
            }
        }
    }
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  c# object null system class