Sample 1:定时监测.
using System;
using System.Collections.Generic;
using System.Text;
using System.Management;
namespace WMITest
{
class Program3
{
static void Main(string[] args)
{
//新建一个WQL查询对象.
WqlEventQuery query = new WqlEventQuery();
//设置WMI事件类名.
query.EventClassName = "__InstanceOperationEvent";
//设置查询时间间隔,一秒钟查询一次.
query.WithinInterval = new TimeSpan(0, 0, 1);
//设置查询条件.WQL语言,和SQL很相似,获取网卡适配器配置变动信息.
query.Condition = "TargetInstance isa \"Win32_NetworkAdapterConfiguration\"";
//新建一个事件观察者对象.
ManagementEventWatcher watcher = new ManagementEventWatcher();
//设置查询对象.
watcher.Query = query;
//设置要监测的时间,监测3分50秒.
watcher.Options.Timeout = new TimeSpan(0, 3, 50);
//获取事件对象.可以人为修改一下DNS服务器地址来激发事件.
ManagementBaseObject e = watcher.WaitForNextEvent();
//获取事件对象的目标实例.
ManagementBaseObject ei = (ManagementBaseObject)e["TargetInstance"];
//下面就可以获取目标事件的一些信息了,比如物理地址(MAC),和IP地址
//物理地址.
Console.WriteLine(ei["MACAddress"].ToString());
//IP地址.
string[] ips = (string[])ei["IPAddress"];
foreach(string ip in ips)
{
Console.WriteLine(ip);
}
//结束观察着对象;
watcher.Stop();
}
}
}
Sample 2:利用事件监测.
using System;
using System.Collections.Generic;
using System.Text;
using System.Management;
namespace WMITest
{
class Program3
{
static void Main(string[] args)
{
//新建一个WQL查询对象.
WqlEventQuery query = new WqlEventQuery();
//设置WMI事件类名.
query.EventClassName = "__InstanceOperationEvent";
//设置查询时间间隔,一秒钟查询一次.
query.WithinInterval = new TimeSpan(0, 0, 1);
//设置查询条件.WQL语言,和SQL很相似,获取网卡适配器配置变动信息.
query.Condition = "TargetInstance isa \"Win32_NetworkAdapterConfiguration\"";
//新建一个事件观察者对象.
ManagementEventWatcher watcher = new ManagementEventWatcher();
//设置查询对象.
watcher.Query = query;
//设置要事件处理者.
watcher.EventArrived += new EventArrivedEventHandler(watcher_EventArrived);
//开始监听.
watcher.Start();
//阻塞线程,等待事件激发.这句有点别扭,最好new个线程来等待监测.
Console.ReadKey();
}
static void watcher_EventArrived(object sender, EventArrivedEventArgs wmievent)
{
//获取事件对象.可以人为修改一下DNS服务器地址来激发事件.
ManagementBaseObject e = wmievent.NewEvent;
//获取事件对象的目标实例.
ManagementBaseObject ei = (ManagementBaseObject)e["TargetInstance"];
//下面就可以获取目标事件的一些信息了,比如物理地址(MAC),和IP地址
//物理地址.
Console.WriteLine(ei["MACAddress"].ToString());
//IP地址.
string[] ips = (string[])ei["IPAddress"];
foreach (string ip in ips)
{
Console.WriteLine(ip);
}
}
}
}
转自http://hi.baidu.com/malecu/blog/item/c9d6f0fa608c2d2f4f4aeab2.html