`
qm504qm
  • 浏览: 12662 次
最近访客 更多访客>>
社区版块
存档分类
最新评论

win7啊,我的纠结,ip啊

 
阅读更多

win7啊,我的纠结,ip啊
2011年05月11日
  Visual C#是微软公司推出的下一代程序开发语言,是微软.Net 框架中的的一个重要组成部分,在推出Visual C#的过程中,微软公司还推出了与之相对应的一个软件开发包--.Net FrameWork SDK。此软件开发包里面封装了许多类、对象。Visual C#就是通过调用这些类、对象来实现许多比较强大的功能。在.Net FrameWork SDK中提供了二个可用于网络编程的名称空间,一个是System.Net,另一个是System..Net.Socket。本文就是利用第一个名称空间中封装的类和对象来读取本地计算机名称和机器中所有的IP地址。 一.概述: 我们知道对于一台计算机来说,他只有一个计算机名称,但是他可以有多个IP地址。例如当计算机通过拨号上网的时候,在验证完用户名和口令以后,就会动态分配一个IP地址,此时计算机就拥有了二个IP地址,一个时自己设定的局域网用的IP地址,另外一个就是拨号上网动态分配的IP地址了。本文就是来探索一下如何读取此二个IP地址和计算机名称。 二.程序设计和运行的环境: (1)微软公司视窗2000 服务器版(2).Net FrameWrok SDK Beta 2版 三.程序设计的主要思路及实现方法: (1).读取计算机的名称:在名称空间System.Net中定义了一个类Dns,在此类中定义了一个比较重要的方法 GetHostName ( ),此方法的返回值就是本地计算机名称。在程序设计中首先要导入System.Net名称空间,然后通过调用Dns类中的GetHostName ( )方法读取本地计算机名称,具体实现的主要语句如下: label1.Text = "主机名称:" + System.Net.Dns.GetHostName ( ) ; (2).读取计算机的拨号上网临时的IP地址和局域网分配的固定IP地址:在程序设计中,我们是通过一个自定义的函数--getIPAddress ( )来读取IP地址的。首先看一下如何读取本地固定的IP地址的。在Dns类中还定义了一个方法GetHostByName ( )。此方法的返回值时IPHostEntry 对象,此对象有一个属性是AddressList,此属性是一个IPAddress类型的数组,包含了计算机此时的所有的IP地址信息。这当中也就包含了拨号上网得到的临时分配的IP地址和局域网固定的IP地址。具体实现语句如下:  四.读取计算机名称本机固定IP地址源程序IP01.cs源程序:  //导入程序用到的名称空间 using System ; using System.Net; using System.Windows.Forms ; using System.Drawing ; public class Form3 : Form { //定义二个标签 private Label label1 ; private Label label2 ; public static void Main ( ) { Application.Run ( new Form3 ( ) ) ; } // 构造窗体 public Form3 ( ) { // 建立标签并且初始化 this.label1 = new System.Windows.Forms.Label ( ) ; this.label2 = new System.Windows.Forms.Label ( ) ; //先继承一个Label 类 label1.Location = new System.Drawing.Point ( 24 , 16 ) ; label2.Location = new System.Drawing.Point ( 44 , 36 ) ; //设定 Label的显示位置 label1.Text = "主机名称:" + System.Net.Dns.GetHostName ( ) ; // 显示本机的计算机名称 label2.Text = "IP 地址:" + getIPAddress ( ) ; // 显示本机的局域网IP地址 label1.Size = new System.Drawing.Size ( 200 , 50 ) ; label2.Size = new System.Drawing.Size ( 200 , 80 ) ; //设定标签的大小 label1.TabIndex = 0 ; label2.TabIndex = 1 ; label1.TextAlign = System.Drawing.ContentAlignment.MiddleCenter ; label2.TextAlign = System.Drawing.ContentAlignment.MiddleCenter ; // 设定标签的对齐方式 this.Text = "获得主机名称和IP地址!" ; this.StartPosition = System.Windows.Forms.FormStartPosition.CenterParen t ; this.AutoScaleBaseSize = new System.Drawing.Size ( 8 , 16 ) ; this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.Fixed3D ; // 设定窗体的边界类型 this.ForeColor = System.Drawing.SystemColors.Desktop ; this.Font = new System.Drawing.Font ( "宋体" , 10 , System.Drawing.FontStyle.Bold ) ; // 设定字体、大小就字体的式样 this.SizeGripStyle = System.Windows.Forms.SizeGripStyle.Hide ; this.ClientSize = new System.Drawing.Size ( 250 , 250 ) ; //把标签加到窗体中 this.Controls.Add ( this.label1 ) ; this.Controls.Add ( this.label2 ) ; } private static string getIPAddress ( ) { System.Net.IPAddress addr; // 获得本机局域网IP地址 addr = new System.Net.IPAddress ( Dns.GetHostByName ( Dns.GetHostName ( ) ) .AddressList [0].Address ) ; return addr.ToString ( ) ; } 
  } 在经过以下编译命令编译后, csc /r:system.dll /r:system.windows.forms.dll /r:system.drawing.dll /t:winexeip01.cs 得到ip01.exe文件,此文件就可以读取本地固定的IP地址。以下是执行后的界面: 
  图01:读取计算机名称和固定IP地址 
  五.读取计算机名称和拨号上网动态分配的IP地址源程序 在前面已经说了,GetHostByName ( )方法的返回值时IPHostEntry 对象,此对象的属性 AddressList,是一个IPAddress类型的数组,包含了计算机此时的所有的IP地址信息。在ip01.cs中AddressList [0].Address是固定的IP地址,而对于上网动态分配的IP地址是.AddressList [1].Address。据此我们可以的得到读取拨号上网动态分配的IP地址的源程序: IP02.cs源程序:  //导入程序用到的名称空间 using System ; using System.Net; using System.Windows.Forms ; using System.Drawing ; public class Form3 : Form { //定义二个标签 private Label label1 ; private Label label2 ; public static void Main ( ) { Application.Run ( new Form3 ( ) ) ; } // 构造窗体 public Form3 ( ) { // 建立标签并且初始化 this.label1 = new System.Windows.Forms.Label ( ) ; this.label2 = new System.Windows.Forms.Label ( ) ; //先继承一个Label 类 label1.Location = new System.Drawing.Point ( 24 , 16 ) ; label2.Location = new System.Drawing.Point ( 44 , 36 ) ; //设定 Label的显示位置 label1.Text = "主机名称:" + System.Net.Dns.GetHostName ( ) ; // 显示本机的计算机名称 label2.Text = "IP 地址:" + getIPAddress ( ) ; // 显示本机的拨号动态分配IP地址 label1.Size = new System.Drawing.Size ( 200 , 50 ) ; label2.Size = new System.Drawing.Size ( 200 , 80 ) ; //设定标签的大小 label1.TabIndex = 0 ; label2.TabIndex = 1 ; label1.TextAlign = System.Drawing.ContentAlignment.MiddleCenter ; label2.TextAlign = System.Drawing.ContentAlignment.MiddleCenter ; // 设定标签的对齐方式 this.Text = "获得主机名称和IP地址!" ; this.StartPosition = System.Windows.Forms.FormStartPosition.CenterParen t ; this.AutoScaleBaseSize = new System.Drawing.Size ( 8 , 16 ) ; this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.Fixed3D ; // 设定窗体的边界类型 this.ForeColor = System.Drawing.SystemColors.Desktop ; this.Font = new System.Drawing.Font ( "宋体" , 10 , System.Drawing.FontStyle.Bold ) ; // 设定字体、大小就字体的式样 this.SizeGripStyle = System.Windows.Forms.SizeGripStyle.Hide ; this.ClientSize = new System.Drawing.Size ( 250 , 250 ) ; //把标签加到窗体中 this.Controls.Add ( this.label1 ) ; this.Controls.Add ( this.label2 ) ; } private static string getIPAddress ( ) { System.Net.IPAddress addr; // 获得拨号动态分配IP地址 addr = new System.Net.IPAddress ( Dns.GetHostByName ( Dns.GetHostName ( ) ) .AddressList [1].Address ) ; return addr.ToString ( ) ; } } 编译完成后,执行可得到如下运行界面: 
  图02:读取计算机名称和动态IP地址 
  六.总结: 本文是通过二个例子来读出机器的计算机名称和不同的IP地址,通过以上二个例子,我们可以看到如果机器有三个或者更多的IP地址,我们也可以通过设定AddressList的不同值来得到机器不同的IP地址。在名称空间System.Net中还提供了很多面向网络编程的的类,这些类的功能是十分巨大的,灵活运用这些类, 
  这是我的一个程序,包括更改MAC地址,和IP地址。 
  ManagementBaseObject   inPar   =   null; 
  ManagementBaseObject   outPar   =   null; 
  ManagementClass   mc   =   new   ManagementClass( "Win32_NetworkAdapterConfiguration "); 
  ManagementObjectCollection   moc   =   mc.GetInstances(); 
  foreach(ManagementObject   mo   in   moc)   
  {   
  if(!   (bool)   mo[ "IPEnabled "])   
  continue;   
  //Set   IPAddress   &   SubnetMask 
  inPar   =   mo.GetMethodParameters( "EnableStatic ");   
  inPar[ "IPAddress "]   =   new   string[]   {   "202.112.152.171 "   }; 
  inPar[ "SubnetMask "]   =   new   string[]   {   "255.255.255.0 "   }; 
  //string   labip   =   labIP.Text.Trim(); 
  //string   labsm   =   labSM.Text.Trim(); 
  //inPar[ "IPAddress "]   =   labip; 
  //inPar[ "SubnetMask "]   =   labsm; 
  outPar   =   mo.InvokeMethod( "EnableStatic ",   inPar,   null);   
  //set   Getway 
  inPar   =   mo.GetMethodParameters( "SetGateways ");   
  inPar[ "DefaultIPGateway "]   =   new   string[]{ "202.112.152.2 "}; 
  //string   labgw   =   labGW.Text.Trim(); 
  //inPar[ "DefaultIPGateway "]   =   labgw; 
  outPar   =   mo.InvokeMethod( "SetGateways ",   inPar,   null);   
  //Set   macAddress 
  RegistryKey   hklm   =   Registry.LocalMachine   ; 
  RegistryKey   software   =   hklm.OpenSubKey   (   "SYSTEM "   ,true)   ;//打开 "SYSTEM "子键 
  RegistryKey   no1   =   software.OpenSubKey   (   "ControlSet001 "   ,true)   ;//打开 "ControlSet001 "子键 
  RegistryKey   no2   =   no1.OpenSubKey   (   "Control "   ,true)   ; 
  RegistryKey   no3   =   no2.OpenSubKey   (   "Class "   ,true)   ; 
  RegistryKey   no4   =   no3.OpenSubKey   (   "{4D36E972-E325-11CE-BFC1-08002bE10318} "   ,true)   ; 
  RegistryKey   no5   =   no4.OpenSubKey   (   "0001 "   ,true)   ; 
  string   networkAddress   =   labMac.Text.Trim(); 
  no5.SetValue   (   "NetworkAddress "   ,   networkAddress)   ; 
  MessageBox.Show( "   lab   OK! ");
  第一次翻译,只想带个头,翻译的不好,希望各位不要笑话我
  相信大家对WMI一定也都有听说过吧,国内的很多网站也多有介绍过
  这里是codeproject上的一篇,我觉得很全面在这里翻译一下希望大
  家评价一下,讨论一下自己编写代码的心得,OK不多说了,翻译了......
  先介绍一下相关知识:
  什么是WMI呢Windows 管理规范 (Windows Management Instrumentation ),它的
  主要功能包括:访问本地主机的一些信息和服务,可以远程管理计算机(当然你必
  须拥有足够的权限)也就是说可以象重起,关机,关闭进程,创建进程等等!
  有了初步了解下面我门开始一些初步的工作吧:
  在这个WMI程序中,我将实现四个基本功能:
  1.Explorer 类似与windows里的资源管理器
  2.SystemInfo 查看你的硬件信息和OS信息
  3.Services  当前正在工作的信息
  4.Processes 当前执行的进程
  (这里是可以管理远程和本地OS的)
  好了,我们要开始实现访问我们的OS了,不过在这之前我们必须要引入System.Management 
  这个命名空间
  下面让我们了解一下控件的状态事件
  我们必须保证是实时的所以必须在这里包涵UpdateStatus(string e)该事件(这是一个自定义的)
  这里主要是希望在点击每个控件时刷新状态栏,可以让用户知道程序在做什么!
  代码事例:
  //控件代码
  //状态事件的代理
  public delegate void Status(string e);
  public event Status UpdateStatus;
  //这里更新状态栏
  UpdateStatus("Hello world.");
  //这里是在主程序里的代码
  //写具体的事件代码
  private void refreshStatusBar(string stringStatus)
  {
  //update status bar
  statusBarStatus.Text = stringStatus;
  }
  下面是具体代码:
  Explorer  Control
  这里首先介绍一下WMI的 Win32_LogicalDisk类(参考Platform SDK: Windows Management Instrumentation),通过它我们可以查看到本地驱动器
  的一些详细情况,我们还需要用到System.Management中的两个类ManagementObjectSearcher
  和ManagementOjbectCollection它们的作用主要是ManagementObjectSearcher将查询到了
  ManagementOjbectCollection该对象的集合中去(这里可以获取的驱动器信息包括 驱动器的名称
  ,类型,描述信息等)当然你也可以只查看驱动器的部分信息可以在ManagementObjectSearcher类
  的构造函数中这样写ManagementObjectSearcher query = new ManagementObjectSearcher("SELECT * From Win32_LogicalDisk "); (参考Platform SDK: Windows Management Instrumentation)
  代码如下:
  //get drive collection 
  ManagementObjectSearcher query = new ManagementObjectSearcher("SELECT * From Win32_LogicalDisk "); 
  ManagementObjectCollection queryCollection = query.Get(); 
  //loop throught each object to get drive information
  foreach ( ManagementObject mo in queryCollection) 
  { 
  switch (int.Parse( mo["DriveType"].ToString())) 
  { 
  case Removable: //removable drives 
  imageIndex = 5; 
  selectIndex = 5; 
  break; 
  case LocalDisk: //Local drives 
  imageIndex = 6; 
  selectIndex = 6; 
  break; 
  case CD: //CD rom drives 
  imageIndex = 7; 
  selectIndex = 7; 
  break; 
  case Network: //Network drives 
  imageIndex = 8; 
  selectIndex = 8; 
  break; 
  default: //defalut to folder 
  imageIndex = 2; 
  selectIndex = 3; 
  break; 
  } 
  //get drive name
  Console.WriteLine("Drive: " + mo["Name"].ToString()); 
  } 
  SystemInfo Control
  该控件主要用来查看本地或远程主机的OS和硬件信息,这里需要用到另外两个
  对象ConnectionOptions和ManagementScope,ConnectionOptions主要是设置
  WMI连接信息的,如用户名和密码,这里我们主要用到它的两个属性UserName和
  Password; ManagementScope对象表示WMI的规范,通过该规范可以访问服务器
  和命名空间的路径已及使用ConnectionOptions中的设置
  请看如下代码:
  //Connect to the remote computer
  ConnectionOptions co = new ConnectionOptions();
  co.Username = textUserID.Text;
  co.Password = textPassword.Text;
  //Point to machine
  System.Management.ManagementScope ms = new System.Management.ManagementScope("\\\\" + 
  stringHostName + "\\root\\cimv2", co);      
  现在我们结合刚才的知识来得到我们要的信息,但我们要得到那些我们想要信息呢?
  那样的话我们就必须要用到ObjectQuery对象,通过它我们可以得到我们想要的查询
  信息.把ObjectQuery对象和ManagementScope对象放入ManagementObjectSearcher对象
  中这样就可以通过我们设置好的规范和我们设置好的查询得到我们想要的结果,当然
  还必须要掉用ManagementObjiectSearcher的Get()方法,它会返回一个ManagementObject
  对象的集合,然后可以通过结合操作来访问到每一个我们要的信息.
  代码如下:
  //Query system for Operating System information
  oq = new System.Management.ObjectQuery("SELECT * FROM Win32_OperatingSystem");
  query = new ManagementObjectSearcher(ms,oq);
  queryCollection = query.Get();
  foreach ( ManagementObject mo in queryCollection)
  {
  //create child node for operating system
  createChildNode(nodeCollection, "Operating System: " + mo["Caption"]);
  createChildNode(nodeCollection, "Version: " + mo["Version"]);
  createChildNode(nodeCollection, "Manufacturer : " + mo["Manufacturer"]);
  createChildNode(nodeCollection, "Computer Name : " +mo["csname"]);
  createChildNode(nodeCollection, "Windows Directory : " + mo["WindowsDirectory"]);
  }
  要是你只是希望查看到本地主机的信息,你就没必要去创建 ConnectionOption, ManagementScope,ObjectQuery 对象,你仅仅只需要把ManagementObjectSearcher
  对象的结果在ManagementObjectCollection集合里去调用Get()方法既可.
  代码如下:
  ManagementObjectSearcher query = new ManagementObjectSearcher("SELECT * From Win32_OperatingSystem");
  ManagementObjectCollection queryCollection = query.Get();
  这里只是介绍了OS信息的方法,其它的如Bios,Memory.Network Connection等信息的查看
  只需要把查询字改改就可以了!(可参考Platform SDK: Windows Management Instrumentation) 
  Service Control控件介绍:
  该控件要用到一个新的查询字"SELECT * FROM Win32_Service",通过它我们就可以
  得到系统中有那些服务存在.为了方便启动和终止一项服务我们可以在ListView中
  动态的创建一个弹出式菜单,当用鼠标左击ListView中的Item的时候,可以用来启动
  或终止一项服务.可以这样来指定你要的服务"SELECT * FROM Win32_Service WHERE
  Name = 'ServiceName'",这个时候我们要调用ManagementObject.InvokeMethod() 
  来指定是终止还是启动一个服务.InvokeMethod()的第一个参数是一个ManagementBaseObject
  的对象.它用作更具体的管理对象类的基类.我通过一个ManagementOperationObserver对象
  管理异步操作和处理异步收到的管理信息和事件。可以由completionHandlerObj.ReturnObject
  (为自定义类的属性)
  属性返回值来判断是否成功.
  代码如下:
  /// 
  /// List view mouse down event to built context menu dynamically 
  /// 
  /// 
  /// 
  private void listViewServices_MouseDown(object sender, System.Windows.Forms.MouseEventArgs e)
  {
  System.Windows.Forms.ListView listViewObject = (System.Windows.Forms.ListView) sender;
  ContextMenu mnuContextMenu = new ContextMenu();
  MenuItem menuItem = new MenuItem();
  ManagementObjectCollection queryCollection;
  //check if right button
  if (e.Button == System.Windows.Forms.MouseButtons.Right) 
  {
  //get service name
  ServiceName = listViewObject.GetItemAt(e.X, e.Y).Text;
  //set list view item
  ServiceItem = listViewObject.GetItemAt(e.X,e.Y);
  //create popup menu
  listViewObject.ContextMenu = mnuContextMenu;
  try
  {
  //get specific service object
  queryCollection = getServiceCollection("SELECT * FROM Win32_Service Where Name = '" + 
  ServiceName + "'");
  foreach ( ManagementObject mo in queryCollection)
  {
  //create menu depending on service state
  if (mo["Started"].Equals(true))
  {
  menuItem.Text = "Stop";
  //set action property
  ServiceAction = "StopService";
  }
  else
  {
  menuItem.Text = "Start";
  ServiceAction = "StartService";
  }
  mnuContextMenu.MenuItems.Add(menuItem);
  // Add functionality to the menu items using the Click event. 
  menuItem.Click  += new System.EventHandler(this.menuItem_Click);
  }
  }
  catch (Exception e1)
  {
  MessageBox.Show("Error: " + e1);
  }
  }
  }
  /// 
  /// List view context menu click event to invoke start/stop service
  /// 
  /// 
  /// 
  private void menuItem_Click(object sender, System.EventArgs e)
  {   
  ManagementObjectCollection queryCollection;
  ListViewItem lvItem;
  //Set up a handler for the asynchronous callback
  ManagementOperationObserver observer = new ManagementOperationObserver(); 
  completionHandler.MyHandler completionHandlerObj = new completionHandler.MyHandler(); 
  observer.ObjectReady += new ObjectReadyEventHandler(completionHandlerObj.Done) ;
  //get specific service object
  queryCollection = getServiceCollection("Select * from Win32_Service Where Name ='" +
  ServiceName + "'");
  //Status 
  updateStatus("Starting/Stopping service..."); 
  foreach ( ManagementObject mo in queryCollection)  
  { 
  //start or stop  service 
  mo.InvokeMethod(observer, ServiceAction, null); 
  } 
  //wait until invoke method is complete  or 5 sec timeout 
  int intCount = 0;  
  while
  (!completionHandlerObj.IsComplete) 
  { 
  if 
  (intCount >  10)
  {
  MessageBox.Show("Terminate process timed out.", "Terminate Process Status");
  break;
  }
  //wait 1/2 sec.
  System.Threading.Thread.Sleep(500); 
  //increment counter
  intCount++;
  } 
  //see if call was successful.
  if (completionHandlerObj.ReturnObject.Properties["ret urnValue"].Value.ToString() == "0")
  { 
  //succeeded
  lvItem = ServiceItem;
  if (ServiceAction == "StartService")
  lvItem.SubItems[2].Text = "Started";
  else
  lvItem.SubItems[2].Text = "Stop";
  }
  else
  {
  //error message
  string stringAction;
  if (ServiceAction == "StartService")
  stringAction = "start";
  else
  stringAction = "stop";
  MessageBox.Show("Failed to " + stringAction + " service " + ServiceName + ".", 
  "Start/Stop Service Failure");
  }
  //clean-up objects
  ServiceName = "";
  ServiceAction = "";
  ServiceItem = null;
  //Status
  updateStatus("Ready");
  this.Update();
  }
  //----------------------------------
  // Completion Handler 
  //----------------------------------
  using System;
  using System.Management;
  namespace completionHandler
  {
  /// 
  /// MyHandler class handle notification when InvokeMethod call is complete
  /// 
  public class MyHandler
  {
  private bool isComplete = false;
  private ManagementBaseObject returnObject;
  /// 
  /// Trigger Done event when InvokeMethod is complete
  /// 
  public void Done(object sender, ObjectReadyEventArgs e)
  { 
  isComplete = true;
  returnObject = e.NewObject;
  }
  /// 
  /// Get property IsComplete
  /// 
  public bool IsComplete 
  {
  get 
  {
  return isComplete;
  }
  }
  /// 
  /// Property allows accessing the result object in the main function
  /// 
  public ManagementBaseObject ReturnObject 
  {
  get 
  {
  return returnObject;
  }
  }
  }
  }
  ProcessesControl控件介绍:
  该控件主要用来显示系统中正在运行的进程,如:用户进程.CPU利用率,
  内存的使用状况.我们可以通过GetOwner(User,Domain)方法来得知进程
  的所有者是谁.User和Domain是入口参数,可是问题是我们如何从InvokeMethod
  中得到这入口参数呢?这里我们需要实现InvokeMethod.一下讨论两种情况
  1.我们不需要异步操作,我们仅仅只需要一个string[]数组就可以完成
  2.当我们需要异步操作的时候也只需要一个completionHandlerObj.ReturnObject 
  属性来收集对象.
  代码如下:
  //------------------------------------------------ - 
  //Get process owner info without the observer object 
  //------------------------------------------------ -- 
  //Createan array containing all arguments for the method
  string[] methodArgs = {"", ""}; 
  //Get process owner info 
  mo.InvokeMethod("GetOwner", methodArgs); 
  //methodArgs[0] - contain process user 
  //methodArgs[1] = contain process domain 
  //-----------------------------------------------
  //Getprocess owner info with the observer object
  //-----------------------------------------------
  mo.InvokeMethod(observer,"GetOwner", null);
  while (!completionHandlerObj.IsComplete) 
  { 
  System.Threading.Thread.Sleep(500); 
  } 
  if (completionHandlerObj.ReturnObject["returnValue"]. ToString() == "0") 
  structProcess.stringUserName = completionHandlerObj.ReturnObject.Properties["User "].Value.ToString();
  else
  structProcess.stringUserName = "";
  下面讨论如何终结进程:
  终结一个指定的进程很类似与上面提到的启动或终止一项服务.
  首先当然是用ManagementObject对象来指定你要的进程,然后调用
  InvokeMethod(observer,"Terminate",null)来终止一个进程.
  代码如下:
  //Set up a handler for the asynchronous callback
  ManagementOperationObserver observer = new ManagementOperationObserver(); 
  completionHandler.MyHandler completionHandlerObj = new completionHandler.MyHandler(); 
  observer.ObjectReady  += new ObjectReadyEventHandler(completionHandlerObj.Done) ;
  //Get ManagementObject for process
  queryCollection = getProcessCollection("Select * from Win32_Process Where ProcessID = '" + ProcessID + "'");
  //Status
  updateStatus("Invoking terminate process");
  foreach ( ManagementObject mo in queryCollection)
  {
  //start or stop service
  mo.InvokeMethod(observer, "Terminate", null);
  }
  //wait until invoke method is complete or 5 sec timeout
  int intCount = 0;
  while (!completionHandlerObj.IsComplete) 
  { 
  if (intCount == 10)
  {
  MessageBox.Show("Terminate process timed out.", "Terminate Process Status");
  break;
  }
  //wait 1/2 sec.
  System.Threading.Thread.Sleep(500); 
  //increment counter
  intCount++;
  } 
  if (intCount != 10)
  {
  //InvokeMethod did not time out
  if (completionHandlerObj.ReturnObject.Properties["ret urnValue"].Value.ToString() == "0")
  { 
  lvItem = ProcessItem;
  lvItem.Remove();
  }
  else
  {
  MessageBox.Show("Error terminating process.", "Terminate Process");
  }
  } 创建进程:
  创建一个新的进程我们需要调用ManagementClass类的InvokeMethod方法来完成
  我们可以通过ManagementClass processClass = New ManagementClass(ms,path,null);
  这条语句来实现一个ManagementClass对象.ms是一个ManagementScope类的实例;
  ,path是一个ManagementPath的实例.ManagementScope来设置Management的范围.
  ManagementPath用来提供一个包装,用于分析和生成 WMI 对象的路径.("Win32_Process")
  在这之前我们还需要调用ManagementClass.InvokeMethod(observer, methodName, inParameters). 
  我们可以通过一个对象数组来一次传递四个参数.inParameters实际上就是一个
  Create Method in Class Win32_Process(参考Platform SDK: Windows Management Instrumentation)
  uint32 Create(string CommandLine,
  string CurrentDirectory,
  Win32_ProcessStartup ProcessStartupInformation,
  uint32* ProcessId);
  Parameters
  CommandLine - [in] Command line to execute. The system adds a null character to the command line, trimming the string if necessary, to indicate which file was actually used. 
  CurrentDirectory -  [in] Current drive and directory for the child process. The string requires that the current directory resolves to a known path. A user can specify an absolute path or a path relative to the current working directory. If this parameter is NULL, the new process will have the same path as the calling process. This option is provided primarily for shells that must start an application and specify the application's initial drive and working directory. 
  ProcessStartupInformation  - [in] The startup configuration of a Windows process. For more information see Win32_ProcessStartup. 
  ProcessId - [out] Global process identifier that can be used to identify a process. The value is valid from the time the process is created until the time the process is terminated 
  例如代码:
  //Create an array containing all arguments for the method
  object[] methodArgs = {stringCommandLine, null, null, 0};
  //Execute the method
  processClass.InvokeMethod (observer, "Create", methodArgs);
  下面的代码是用来创建并插入一个新的进程.我们可以写一个CreateProcess 
  函数通过参数stringCommandLine来传递一个你希望创建的进程.如你可以
  这样写 CreateProcess("Calc.exe"), 这时候你就可以创建一个计算器
  进程了,下面是个例子.
  代码如下;
  /// 
  /// Invoke method 'Create' on local or remote machine
  /// 
  /// 
  private void CreateProcess(string stringCommandLine)
  {   
  //Set up a handler for the asynchronous callback
  ManagementOperationObserver observer = new ManagementOperationObserver(); 
  completionHandler.MyHandler completionHandlerObj = new completionHandler.MyHandler(); 
  observer.ObjectReady  += new ObjectReadyEventHandler(completionHandlerObj.Done) ;
  string stringMachineName = "";
  //Connect to the remote computer
  ConnectionOptions co = new ConnectionOptions();
  if (radioMachine.Checked == true)
  {
  stringMachineName = "localhost";
  }
  else
  {
  stringMachineName = textIP.Text;
  }
  if (stringMachineName.Trim().Length == 0)
  {
  MessageBox.Show("Must enter machine IP address or name.");
  return;
  }
  //get user and password
  if (textUserID.Text.Trim().Length   > 0)
  {
  co.Username = textUserID.Text;
  co.Password = textPassword.Text;
  }
  //Point to machine
  System.Management.ManagementScope ms = new System.Management.ManagementScope("\\\\" + 
  stringMachineName + "\\root\\cimv2", co);      
  //get process path
  ManagementPath path = new ManagementPath( "Win32_Process");
  //Get the object on which the method will be invoked
  ManagementClass processClass = new ManagementClass(ms,path,null);
  //Status
  updateStatus("Create process " + stringCommandLine + ".");
  //Create an array containing all arguments for the method
  object[] methodArgs = {stringCommandLine, null, null, 0};
  //Execute the method
  processClass.InvokeMethod (observer, "Create", methodArgs);
  //wait until invoke method is complete or 5 sec timeout
  int intCount = 0;
  while (!completionHandlerObj.IsComplete) 
  { 
  if (intCount > 10)
  {
  MessageBox.Show("Create process timed out.", "Terminate Process Status");
  break;
  }
  //wait 1/2 sec.
  System.Threading.Thread.Sleep(500); 
  //increment counter
  intCount++;
  } 
  if (intCount != 10)
  {
  //InvokeMethod did not time out
  //check for error
  if (completionHandlerObj.ReturnObject.Properties["ret urnValue"].Value.ToString() == "0")
  {
  //refresh process list
  this.Refresh();
  }
  else
  {
  MessageBox.Show("Error creating new process.", "Create New Process");
  }
  }
  //Status
  updateStatus("Ready");
  this.Update();
  }
  总结:
  这里只是做了一个使用WMI的例子.我们大体可以通过这个简单的例子
  了解一下WMI究竟可以做那些事情.我想,我在代码中的注释可以很方便
  让大家了解WMI.
  下面这个列表可以让你明白WMI能处理那些问题:
  *控制你的软硬件
  *监管事件
  *执行一个基于事件的描述
  *通过事件来发送E-mail
  Windows 管理规范 (WMI) 是可伸缩的系统管理结构,它采用一个统一的、基于标准的、可扩展的面向对象接口。WMI 为您提供与系统管理信息和基础 WMI API 交互的标准方法。WMI 主要由系统管理应用程序开发人员和管理员用来访问和操作系统管理信息。
  WMI 可用于生成组织和管理系统信息的工具,使管理员或系统管理人员能够更密切地监视系统活动。例如,可以使用 WMI 开发一个应用程序,用于在 Web 服务器崩溃时呼叫管理员。 将 WMI 与 .NET 框架一起使用
  WMI 提供了大量的规范以便为许多高端应用程序(例如,Microsoft Exchange、Microsoft SQL Server 和 Microsoft Internet 信息服务 (IIS))实现几乎任何管理任务。管理员可以执行下列任务:  监视应用程序的运行状况。 
  检测瓶颈或故障。 
  管理和配置应用程序。 
  查询应用程序数据(使用对象关系的遍历和查询)。 
  执行无缝的本地或远程管理操作。 
  WMI 结构由以下三层组成:  客户端 
  使用 WMI 执行操作(例如,读取管理详细信息、配置系统和预订事件)的软件组件。  对象管理器 
  提供程序与客户端之间的中间装置,它提供一些关键服务,如标准事件发布和预订、事件筛选、查询引擎等。  提供程序 
  软件组件,它们捕获实时数据并将其返回到客户端应用程序,处理来自客户端的方法调用并将客户端链接到所管理的基础结构。  通过定义完善的架构向客户端和应用程序无缝地提供了数据和事件以及配置系统的能力。在 .NET 框架中,System.Management 命名空间提供了用于遍历 WMI 架构的公共类。
  除了 .NET 框架,还需要在计算机上安装 WMI 才能使用该命名空间中的管理功能。如果使用的是 Windows Millennium Edition、Windows 2000 或 Windows XP,那么已经安装了 WMI。否则,将需要从 MSDN 下载 WMI。 System.Management 命名空间是 .NET 框架中的 WMI 命名空间。此命名空间包括下列支持 WMI 操作的第一级类对象:  ManagementObject 或 ManagementClass:分别为单个管理对象或类。 
  ManagementObjectSearcher:用于根据指定的查询或枚举检索 ManagementObject 或 ManagementClass 对象的集合。 
  ManagementEventWatcher:用于预订来自 WMI 的事件通知。 
  ManagementQuery:用作所有查询类的基础。 
  System.Management 类的使用编码范例对 .NET 框架环境很适合,并且 WMI 在任何适当的时候均使用标准基框架。例如,WMI 广泛利用 .NET 集合类并使用推荐的编码模式,如 .NET 异步操作的"委托"模式。因此,使用 .NET 框架的开发人员可以使用他们的当前技能访问有关计算机或应用程序的管理信息。 使用 WMI 管理应用程序 | 检索管理对象的集合 | 查询管理信息 | 预订和使用管理事件 | 执行管理对象的方法 | 远程处理和连接选项 | 使用强类型对象
  获取CPU序列号代码
  string cpuInfo = "";//cpu序列号
  ManagementClass cimobject = new ManagementClass("Win32_Processor");
  ManagementObjectCollection moc = cimobject.GetInstances();
  foreach(ManagementObject mo in moc)
  {
  cpuInfo = mo.Properties["ProcessorId"].Value.ToString();
  Console.WriteLine(cpuInfo);
  Console.ReadLine();
  }
  获取网卡硬件地址
  using System.Management;
  ...
  ManagementClass mc = new ManagementClass("Win32_NetworkAdapterConfiguration ");
  ManagementObjectCollection moc = mc.GetInstances();
  foreach(ManagementObject mo in moc)
  {
  if((bool)mo["IPEnabled"] == true)
  Console.WriteLine("MAC address\t{0}", mo["MacAddress"].ToString());
  mo.Dispose();
  }
  }
  获取硬盘ID
  String HDid;
  ManagementClass cimobject = new ManagementClass("Win32_DiskDrive");
  ManagementObjectCollection moc = cimobject.GetInstances();
  foreach(ManagementObject mo in moc)
  {
  HDid = (string)mo.Properties["Model"].Value;
  MessageBox.Show(HDid  ); 
  }
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics