由于业务需要需要对本机的服务进行监视,网上查询一些,关于WMI 的信息。于是就有了如下代码!
记录一下,以便日后再用到~
关键几个地方!
项目需要引用 System.Management
ManagementEventWatcher MEW = null;
private void Form1_Load(object sender, EventArgs e)
{
try
{
//连接本地 Windows Management Instrumentation (WMI)
ManagementScope scope = new ManagementScope(@"//localhost/root/cimv2");
scope.Connect();
WqlEventQuery query = new WqlEventQuery("__InstanceModificationEvent", new TimeSpan(0, 0, 1), "TargetInstance isa 'Win32_Service' ");
MEW = new ManagementEventWatcher(scope, query);
MEW.EventArrived += new EventArrivedEventHandler(MEW_EventArrived);
MEW.Stopped += new StoppedEventHandler(MEW_Stopped);
MEW.Start();
}
catch(Exception E)
{
MessageBox.Show(E.Message);
}
}
void MEW_Stopped(object sender, StoppedEventArgs e)
{
}
void MEW_EventArrived(object sender, EventArrivedEventArgs e)
{
try
{
ManagementBaseObject Mbo = ((ManagementBaseObject)e.NewEvent["TargetInstance"]);
/* 对于不清楚 ManagementBaseObject 遍历一下对象 属性
foreach (PropertyData item in AS.Properties)
{
}
* */
MessageBox.Show("系统服务 " + Mbo["Caption"].ToString() + "调整为:" + Mbo["State"].ToString());
}
catch
{
}
}
private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
MEW.Stop();
}
后来找到一个对WMI 操作比较好的 类库,效果不错!
http://www.codeproject.com/KB/dotnet/EasyWMILibrary.aspx
对于基础的WMI 信息获取,写起来方便多了!不过对于监控服务,还得使用
ManagementEventWatcher !
关于WQL 中查询 的 WMI Classes 参看
http://msdn.microsoft.com/en-us/library/aa394554.aspx