使用WMI控制Windows进程

本文主要介绍两种WMI的进行操作:检查进程是否存在、创建新进行

代码如下:

+展开
-C#
using System; 
using System.Collections.Generic; 
using System.Text; 
using System.Management; 
using System.Threading; 

namespace TJVictor.WMI 

    public class Win32_Process:WMIBaseClass 
    { 
        #region Property 
        private int timeout = 30; 
        public int TimeOut 
        { 
            get { return timeout; } 
            set { timeout = value; } 
        } 

        private string wqlSelect = "select * FROM Win32_Process where Name='{0}'"
        #endregion 

        #region Construction 
        public Win32_Process() 
            : base() 
        { 
            base.Connection(); 
        } 

        public Win32_Process(string domain, string Ip, string user, string psd) 
            : base(domain, Ip, user, psd) 
        { 
            base.Connection(); 
        } 
        #endregion 

        #region public function 
        public bool IsProcessExist(string name) 
        { 
            if (!GetSelectQueryCollection(wqlSelect,name).Count.Equals(0)) 
                return true
            return false
        } 

        public void CreateProcess(string name) 
        { 
            ManagementClass processClass = new ManagementClass("Win32_Process"); 
            processClass.Scope = base.Scope; 

            ManagementBaseObject mbo = processClass.GetMethodParameters("Create"); 
            mbo["CommandLine"] = string.Format(name); 
            ManagementBaseObject result = processClass.InvokeMethod("Create", mbo, null); 
            //检测执行结果 
            CheckExceptionClass.CheckProcessException(int.Parse(result["returnValue"].ToString())); 
            //检测进程是否执行完成 
            int tempTimeout = this.timeout; 
            while (!GetSelectQueryCollection("select * FROM Win32_Process where ProcessID='{0}'",result["ProcessID"].ToString()).Count.Equals(0)) 
            { 
                if (tempTimeout.Equals(0)) 
                { 
                    throw new TJVictor.WMI.WmiException.ProcessException( 
                        string.Format("在 {0} 上执行 {1} 操作失败,执行超时"base.Ip, name)); 
                } 
                tempTimeout--; 
                Thread.Sleep(1000); 
            } 
        } 
        #endregion 
    } 
}


如需转载,请注明本文原创自CSDN TJVictor专栏:http://blog.csdn.net/tjvictor

加支付宝好友偷能量挖...


评论(0)网络
阅读(100)喜欢(0)Asp.Net/C#/WCF