软件方面有操作系统、系统中安装的软件、正在运行的进程等等。网络方面有域、工作组等等。利用WMI可以访问上面的全部信息,但是如果向上面一样的利用分项来访问的话会很麻烦。为此,WMI提供了一种类似SQL语句的查询语句,可以通过查询语句获得WMI对象下的子项。
下面是一个遍历系统中安装的网卡并返回网卡MAC地址的代码:
Private Function MACAddress() As String
Set objs = GetObject("winmgmts:").ExecQuery( _
"SELECT MACAddress " & _
"FROM Win32_NetworkAdapter " & _
"WHERE " & _
"((MACAddress Is Not NULL) " & _
"AND (Manufacturer <> " & _
"‘Microsoft‘))")
For Each obj In objs
MACAddress = obj.MACAddress
Exit For
Next obj
End Function
上面的代码获得WMI对象,然后运行ExecQuery执行一个WMI查询语句获得安装的网卡并返回网卡的MAC地址。
WMI还支持事件处理,让程序可以处理系统事件,例如程序运行、关闭,可移动驱动器的插入、取出等。下面是一个可以对系统中运行程序进行监控的程序。
首先建立一个新工程,然后点击菜单的 project references 项,在references列表中选中Microsoft WMI Scripting Library将WMI对象库加入工程中。然后在Form1中加入一个ListBox控件,然后在Form1中加入以下代码:
Option Explicit
Dim Locator As SWbemLocator
Dim Services As SWbemServices
Dim WithEvents StatusSink As SWbemSink
Private Sub KillEvents()
StatusSink.Cancel
Set StatusSink = Nothing
End Sub
Private Sub Form_Load()
Dim Query As String
Set StatusSink = New SWbemSink
Set Locator = CreateObject("WbemScripting.SWbemLocator")
Set Services = Locator.ConnectServer()
Query = "SELECT * FROM __InstanceCreationEvent "
Query = Query + "WITHIN 1 "
Query = Query + "WHERE TargetInstance ISA ‘Win32_Process‘"
Services.ExecNotificationQueryAsync StatusSink, Query
End Sub
Private Sub StatusSink_OnObjectReady(ByVal StatusEvent As SWbemObject, _
ByVal EventContext As SWbemNamedValueSet)
Dim arr
Dim strQue As String
Dim i As Integer
List1.Clear
arr = Split(StatusEvent.GetObjectText_, Chr(10))
For i = LBound(arr) To UBound(arr)
List1.AddItem arr(i)
Next i
End Sub
Private Sub StatusSink_OnCompleted(ByVal HResult As WbemErrorEnum, _
ByVal ErrorObject As SWbemObject, _
ByVal EventContext As SWbemNamedValueSet)
If HResult <> wbemErrCallCancelled Then
‘错误处理
End If
End Sub
在上面的程序中定义了一个SWbemSink对象StatusSink,然后建立一个SWbemServices对象Server,并将StatusSink连接到Server对象上。这样就可以通过StatusSink监控程序的运行。
运行程序,然后任意运行一个程序,在Form1的ListBox中就可以列出运行的程序的信息。
WMI应用最强大的一面是可以通过WEB页面来实现远程管理。下面我们来建立一个HTML页面,该页面可以实现向上面的VB程序一样动态监控系统中运行的程序。监控系统中程序运行的HTML代码如下:
<html>
<head>
<object ID="mysink" CLASSID= "CLSID:75718C9A-F029-11d1-A1AC-