监视系统服务

由于业务需要需要对本机的服务进行监视,网上查询一些,关于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

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值