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-00C04FB6C223"></object>
</head>
<SCRIPT>
function window.onload()
{
var locator = new ActiveXObject ("WbemScripting.SWbemLocator");
var service = locator.ConnectServer();
szQuery = "SELECT * FROM __InstanceCreationEvent ";
szQuery += "WITHIN 1 ";
szQuery += "WHERE TargetInstance ISA 'Win32_Process'";
service.ExecNotificationQueryAsync(mysink,szQuery);
}
</SCRIPT>
<script FOR="mysink" EVENT="OnObjectReady(obj, objAsyncContext)">
document.all.info.innerHTML += obj.TargetInstance.Name + "<br>";
</script>
<body>
<span ID="info"></span>
</body>
</html>
保存代码为Htm后缀的页面文件。双击打开网页,然后运行一个程序,在网页上就可以列出
运行的程序的文件名。
以上简要的介绍了一下WMI的应用,实际上WMI对象的操作是十分复杂,功能也是很强大的,例如你可以通过WMI在服务器上监控整个局域网上的计算机、向局域网上的计算机批量安装软件(例如杀毒软件)。通过页面远程访问服务器,控件服务器运行程序,添加用户等。
……