WEB开发网
开发学院软件开发VC WMI(Windows管理规范)的一个实现 阅读

WMI(Windows管理规范)的一个实现

 2006-07-20 11:39:52 来源:WEB开发网   
核心提示: ManagementObjectSearcher query = new ManagementObjectSearcher("SELECT * From Win32_OperatingSystem");ManagementObjectCollection queryCo
ManagementObjectSearcher query = new ManagementObjectSearcher("SELECT * From Win32_OperatingSystem");
ManagementObjectCollection queryCollection = query.Get();

SystemInfo控制也用于显示计算机相关的其他信息:系统制造商,处理器,BIOS,时区,内存、网络连接、显卡等等。用于查询这些信息的代码只是在SQL查询语句和返回属性上不同而已,所以为了减少篇幅我就不把代码写出来了。具体的代码你可以看下载包里的内容。

Service 控制

Service控制使用了这样的一个查询来返回系统中所有服务的信息:

SELECT * FROM Win32_Service

为了能启动或者停止一个服务,我为ListView动态地创建了一个弹出式菜单(上下文菜单)。你在列表的某个项上单击鼠标右键时,一个启动或停止服务(依赖于服务的当前运行状态)的菜单就会弹出。当菜单项被点击后,我需要利用这样的查询语句获得该服务的ManagementObject对象:

SELECT * FROM Win32_Service WHERE Name = ''ServiceName''

接着我就可以通过调用ManagementObject.InvokeMethod()方法来启动或者停止该服务了。InvokeMethod()方法的第一个参数是一个Observer。我传递一个ManagementOperationObserver对象给这个方法,来管理这些异步操作,以及相应的异步事件与信息。通过检查返回的completionHandlerObj.ReturnObject的returnValue属性,我们就可以确定操作是否成功了。

///
/// List view的鼠标右击事件导致动态上下文菜单的生成
///
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;
  //是否是鼠标右键单击
  if (e.Button == System.Windows.Forms.MouseButtons.Right)
  {
    //取得服务的名称
    ServiceName = listViewObject.GetItemAt(e.X, e.Y).Text;
    //取得列表项
    ServiceItem = listViewObject.GetItemAt(e.X,e.Y);
    //创建弹出式菜单
    listViewObject.ContextMenu = mnuContextMenu;
    try
    {
      //取得特定的服务对象
      queryCollection = getServiceCollection("SELECT * FROM Win32_Service Where Name =
    ''" + ServiceName + "''");
      foreach ( ManagementObject mo in queryCollection)
      {
        //据服务的当前状态创建相应的菜单
        if (mo["Started"].Equals(true))
        {
          menuItem.Text = "Stop";
          //设置动作Action属性
          ServiceAction = "StopService";
        }
        else
        {
          menuItem.Text = "Start";
          ServiceAction = "StartService";
        }
        mnuContextMenu.MenuItems.Add(menuItem);
        // 给菜单项挂上事件处理函数
        menuItem.Click += new System.EventHandler(this.menuItem_Click);
      }
    }
    catch (Exception e1)
    {
      MessageBox.Show("Error: " + e1);
    }
  }
}
///
/// List view上下文菜单的事件响应函数
///
///
///
private void menuItem_Click(object sender, System.EventArgs e)
{ 
  ManagementObjectCollection queryCollection;
  ListViewItem lvItem;
  //设置一个异步回调函数的句柄
  ManagementOperationObserver observer = new ManagementOperationObserver();
  completionHandler.MyHandler completionHandlerObj = new completionHandler.MyHandler();
  observer.ObjectReady += new ObjectReadyEventHandler(completionHandlerObj.Done);
  //获得特定的服务对象
  queryCollection = getServiceCollection("Select * from Win32_Service Where Name =''" +
              ServiceName + "''");
  
  //更新状态条
  updateStatus("Starting/Stopping service...");
  
  foreach ( ManagementObject mo in queryCollection) 
  {
    //启动或者停止服务
    mo.InvokeMethod(observer, ServiceAction, null);
  }
  //等待,直到invoke调用完成或者超时5秒后
  
  int intCount = 0; 
  while(!completionHandlerObj.IsComplete)
  {
    if
    (intCount > 10)
    {
      MessageBox.Show("Terminate process timed out.", "Terminate Process Status");
      break;
    }
    //等待0.5秒
    System.Threading.Thread.Sleep(500);
  
    //增加计数器
    intCount++;
  }
  //检查是否成功执行了
  if (completionHandlerObj.ReturnObject.Properties["returnValue"].Value.ToString() == "0")
  {
    //成功
    lvItem = ServiceItem;
    if (ServiceAction == "StartService")
      lvItem.SubItems[2].Text = "Started";
    else
      lvItem.SubItems[2].Text = "Stop";
  }
  else
  {
    //错误信息
    string stringAction;
    if (ServiceAction == "StartService")
      stringAction = "start";
    else
      stringAction = "stop";
    MessageBox.Show("Failed to " + stringAction + " service " + ServiceName + ".",
                    "Start/Stop Service Failure");
  }
  //清除对象
  ServiceName = "";
  ServiceAction = "";
  ServiceItem = null;
  //更新状态条
  updateStatus("Ready");
  this.Update();
}
//----------------------------------
// 完整的处理器
//----------------------------------
using System;
using System.Management;
namespace completionHandler
{
  ///
  /// MyHandler类在InvokeMethod()调用完成后处理通知
  ///
  public class MyHandler
  {
    private bool isComplete = false;
    private ManagementBaseObject returnObject;
      
    ///
    /// 当InvokeMethod完成后触发Done事件
    ///
    public void Done(object sender, ObjectReadyEventArgs e)
    {
      isComplete = true;
      returnObject = e.NewObject;
    }
    ///
    /// 取IsComplete属性
    ///
    public bool IsComplete
    {
      get
      {
        return isComplete;
      }
    }
    ///
    /// 属性允许访问主函数里的返回结果
    ///
    public ManagementBaseObject ReturnObject
    {
      get
      {
        return returnObject;
      }
    }
  }
}

Process 控制

上一页  1 2 3 4 5 6 7 8  下一页

Tags:WMI Windows 管理规范

编辑录入:爽爽 [复制链接] [打 印]
赞助商链接