利WMI实现监视局域网计算机CPU使用情况

       由于近期项目有可能需要使用到WMI技术,因此这段时间有机会学习一下这种技术。本来以为是挺复杂的东西,没想到这方面的资源还是挺多,复杂的东西MS都帮你完成了;.NET FrameWork还直接支持了这种功能的调用,只要花上一点时间就能够写一些基于WIN系统简单监控程序。为了体验一下于是做一个简单的局域网计算机CPU监视程序;.Net FrameWork提供了System.Management名称空间下的一系列对象来处理WMI功能,虽然使用相关的对象并不多,但是WMI Classes整个库还是很庞大的;当然没有必要全部都记录下来当你需要时从MSDN获取就可以了。在使用的过程中主要用ManagementObjectSearcher ManagementQuery 派生的类来查询计算机的资源。

下面是获取计算机的CPU利用率信息:

ConnectionOptions Conn = new ConnectionOptions();

Conn.EnablePrivileges = true;

//如果是登陆其他电脑就需要提供用户名和密码

//Conn.Username = "administrator";

//Conn.Password = "";

System.Management.ManagementScope Ms = new System.Management.ManagementScope("\\\\localhost\\root\\cimv2", Conn);     

System.Management.ObjectQuery Query = new System.Management.ObjectQuery("select *  from Win32_Processor ");

ManagementObjectSearcher Searcher = new ManagementObjectSearcher(Ms,Query);

WMI是支持以SQL语句的方式来查询,对于有SQL语句操作经验的开发人员来说基本上不用学习;只是根据需要的情况查询相关的WMI Classe就可以了。如果需要条件过虑的情况下直接套用where,对于WMI Class的相关成员可以从MSDN得到相关详细的资料。

Win32_Processor成员描述:

class Win32_Processor : CIM_Processor
{
  uint16 AddressWidth;
  uint16 Architecture;
  uint16 Availability;
  string Caption;
  uint32 ConfigManagerErrorCode;
  boolean ConfigManagerUserConfig;
  uint16 CpuStatus;
  string CreationClassName;
  uint32 CurrentClockSpeed;
  uint16 CurrentVoltage;
  uint16 DataWidth;
  string Description;
  string DeviceID;
  boolean ErrorCleared;
  string ErrorDescription;
  uint32 ExtClock;
  uint16 Family;
  datetime InstallDate;
  uint32 L2CacheSize;
  uint32 L2CacheSpeed;
  uint32 L3CacheSize;
  uint32 L3CacheSpeed;
  uint32 LastErrorCode;
  uint16 Level;
  uint16 LoadPercentage;
  string Manufacturer;
  uint32 MaxClockSpeed;
  string Name;
  uint32 NumberOfCores;
  uint32 NumberOfLogicalProcessors;
  string OtherFamilyDescription;
  string PNPDeviceID;
  uint16 PowerManagementCapabilities[];
  boolean PowerManagementSupported;
  string ProcessorId;
  uint16 ProcessorType;
  uint16 Revision;
  string Role;
  string SocketDesignation;
  string Status;
  uint16 StatusInfo;
  string Stepping;
  string SystemCreationClassName;
  string SystemName;
  string UniqueId;
  uint16 UpgradeMethod;
  string Version;
  uint32 VoltageCaps;

};

可以通过LoadPercentage成员获取CPU的利用率。

ManagementObjectCollection ReturnCollection = Searcher.Get();

foreach(ManagementObject item in ReturnCollection)

{

     Console.WriteLine(item["LoadPercentage"]);

}

查询会返回一个对象集,因为实际情况可能有多个CPU;因此通过遍历的方式来把具体CPU的信息显示出来。

最终实现的效果图:


以上显示并没有考虑多
CPU的情况,如果想获取当前CPU更详细的信息可以通过Win32_PerfRawData_PerfOS_Processor来查询。对于相关WMI Classe是否具备可操作方法,具体查看相关WMI Classe的描述文档:

http://msdn.microsoft.com/library/en-us/wmisdk/wmi/wmi_reference.asp?frame=true

下载例程代码

posted on 2006-09-14 09:28  henry  阅读(4710)  评论(8编辑  收藏  举报

导航