天道酬勤

博观而约取,厚积而薄发!
  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

如何使用WMI获取进程信息 (转载)

Posted on 2010-04-29 15:39  Happy Coding  阅读(1293)  评论(0编辑  收藏  举报

最近发现一个比较有趣的东西,WMI。

MSDN:Windows Management Instrumentation (WMI) 是 Windows 操作系统的一个组件,允许通过编程方式访问企业环境中的管理信息。

 

以下示例演示如何使用WMI获得本地机器的进程列表(当然,WMI也能获得远程机器的进程列表,远不只例子中的功能),示例代码是我简化codeproject的例子而来:

 

//用于表示进程信息的结构

public struct structProcessInfo

{

    //进程名

     public string stringName;

    //进程ID

     public string stringProcessID;

    //父进程ID

     public string stringParentProcessID;

    //用户名

     public string stringUserName;

}

 

public class ProcessesInfo

{

     private structProcessInfo _value;

     public structProcessInfo Value

     {

         get {return _value;}

         set {_value = value;}

     }

}

 

//用于保存进程信息的字典类,继承于NameObjectCollectionBase

public class ProcessesDictionary : NameObjectCollectionBase

{

    public void Clear()

    {

        BaseClear();

    }

 

    public void Add(string name, ProcessesInfo processObj)

    {

        BaseAdd(name, processObj);

    }

 

    public void Remove(string name)

    {

        BaseRemove(name);

    }

 

    public void RemoveAt(int index)

    {

        BaseRemoveAt(index);

    }

 

    public ProcessesInfo this[int index]

    {

        get { return (ProcessesInfo)BaseGet(index); }

        set { BaseSet(index, value); }

    }

 

    public ProcessesInfo this[string name]

    {

        get { return (ProcessesInfo)BaseGet(name); }

        set { BaseSet(name, value); }

    }

}

 

=  =  =  =  =  =  =  =  =  =  =  =  =  =  =  =  =  =  =  =  =  =  =  =  =  =  =  =  =  =

 

//用于表示进程CPU及内存使用情况的结构

public struct structPerformance

{

    public string stringPercentProcessorTime;

    public string stringVirtualBytes;

}

 

public class ProcessPerf

{

    private structPerformance _value;

 

    public structPerformance Value

    {

        get { return _value; }

        set { _value = value; }

    }

}

 

//用于保存进程CPU及内存使用情况的字典类

public class ProcessesPerformanceDictionary : NameObjectCollectionBase

{

    public void Clear()

    {

        BaseClear();

    }

 

    public void Add(string name, ProcessPerf processPerformance)

    {

        BaseAdd(name, processPerformance);

    }

 

    public void Remove(string name)

    {

        BaseRemove(name);

    }

 

    public void RemoveAt(int index)

    {

        BaseRemoveAt(index);

    }

 

    public ProcessPerf this[int index]

    {

        get { return (ProcessPerf)BaseGet(index); }

        set { BaseSet(index, value); }

    }

 

    public ProcessPerf this[string name]

    {

        get { return (ProcessPerf)BaseGet(name); }

        set { BaseSet(name, value); }

    }

}

 

=  =  =  =  =  =  =  =  =  =  =  =  =  =  =  =  =  =  =  =  =  =  =  =  =  =  =  =  =  =

 

//表示ManagementObject对象的异步调用方法是否完成

public class MyHandler

{

    private bool isComplete = false;

    private ManagementBaseObject returnObject;

 

    public void Done(object sender, ObjectReadyEventArgs e)

    {

        isComplete = true;

        returnObject = e.NewObject;

    }

 

    public bool IsComplete

    {

        get

        {

            return isComplete;

        }

    }

 

    public ManagementBaseObject ReturnObject

    {

        get

        {

            return returnObject;

        }

    }

}

 

=  =  =  =  =  =  =  =  =  =  =  =  =  =  =  =  =  =  =  =  =  =  =  =  =  =  =  =  =  =

 

一个窗体,添加一个ListView:lvProcess,一个Button:btList用于显示进程列表,一个Button:btClose用于关闭窗体:

private void btList_Click(object sender, EventArgs e)

{

    this.lvProcess.Items.Clear();

 

    ManagementOperationObserver observer = new ManagementOperationObserver();

    MyHandler invokeHandler = new MyHandler();

    observer.ObjectReady += new ObjectReadyEventHandler(invokeHandler.Done);

 

    ProcessesDictionary pDict = new ProcessesDictionary();

    ProcessesPerformanceDictionary perDict = new ProcessesPerformanceDictionary();

 

    ProcessesInfo pInfo;

    structProcessInfo pStruct;

 

    ProcessPerf perInfo;

    structPerformance perStruct;

 

    string[] lvData = new string[5];

 

    #region 获取进程名称、ID、父进程ID、进程所属用户名

    ManagementObjectCollection moc = this.ExecSearch("SELECT * FROM Win32_Process");

    if (moc == null)

    {

        MessageBox.Show("Error:null");

        return;

    }

 

    foreach (ManagementObject mo in moc)

    {

        pInfo = new ProcessesInfo();

        pStruct = new structProcessInfo();

        pStruct.stringName = mo["Name"].ToString();

        pStruct.stringProcessID = mo["ProcessID"].ToString();

        pStruct.stringParentProcessID = mo["ParentProcessID"].ToString();

 

        mo.InvokeMethod(observer, "GetOwner", null);

        while (!invokeHandler.IsComplete)

        {

            System.Threading.Thread.Sleep(500);

        }

 

        //判断获取用户名的操作是否成功

        if (invokeHandler.ReturnObject["returnValue"].ToString() == "0")

        {

            pStruct.stringUserName = invokeHandler.ReturnObject.Properties["User"].Value.ToString();

        }

        else

        {

            pStruct.stringUserName = "";

        }

 

        //保存该进程信息到字典类中

        pInfo.Value = pStruct;

        pDict.Add(mo["ProcessID"].ToString(), pInfo);

    }

    #endregion

 

    #region 获得进程的CPU及内存使用情况

    ManagementObjectCollection moc1 = this.ExecSearch("SELECT * FROM Win32_PerfFormattedData_PerfProc_Process");

    if (moc1 == null)

    {

        MessageBox.Show("Error:null");

        return;

    }

 

    foreach (ManagementObject mo1 in moc1)

    {

        perInfo = new ProcessPerf();

        perStruct = new structPerformance();

 

        perStruct.stringPercentProcessorTime = mo1.Properties["PercentProcessorTime"].Value.ToString();

        perStruct.stringVirtualBytes = mo1["VirtualBytes"].ToString();

 

        //添加CPU及内存使用情况到字典类中

        perInfo.Value = perStruct;

        perDict.Add(mo1["IDProcess"].ToString(), perInfo);

        perInfo = null;

    }

    #endregion

 

    #region 显示列表

    foreach (string stringProcessID in pDict)

    {

        pStruct = pDict[stringProcessID].Value;

        lvData[0] = pStruct.stringName.ToString();

        lvData[4] = pStruct.stringProcessID.ToString();

        lvData[1] = pStruct.stringUserName.ToString();

 

        try

        {

            lvData[2] = perDict[pStruct.stringProcessID.ToString()].Value.stringPercentProcessorTime.ToString();

            lvData[3] = perDict[pStruct.stringProcessID.ToString()].Value.stringVirtualBytes.ToString();

        }

        catch (NullReferenceException)

        {

            //无法获取CPU及内存情况

            lvData[2] = "0";

            lvData[3] = "0";

        }

 

        ListViewItem lvItem = new ListViewItem(lvData, 0);

        lvProcess.Items.Add(lvItem);

    }

    #endregion

 

    pDict.Clear();

    pDict = null;

    perDict.Clear();

    perDict = null;

}

 

/// <summary>

/// 执行查询

/// </summary>

/// <param>查询语句</param>

/// <returns></returns>

private ManagementObjectCollection ExecSearch(string command)

{

    ManagementObjectCollection moc = null;

    ObjectQuery objQuery = new ObjectQuery(command);

    string stringMachineName = "localhost";

    ManagementScope scope = new ManagementScope("\\\\" + stringMachineName + "\\root\\cimv2");

    ManagementObjectSearcher searcher = new ManagementObjectSearcher(scope, objQuery);

 

    try

    {

        moc = searcher.Get();

    }

    catch (Exception x)

    {

        MessageBox.Show("Error:" + x.Message);

    }

 

    return moc;

}

 

 

private void btClose_Click(object sender, EventArgs e)

{

    this.Close();

}