将.Net ManagementBaseObject转换为ManagementObject
问题描述:
我正尝试使用以下代码写出在计算机上启动的所有进程。我的问题是EventArrived方法传递了一个EventArrivedEventArgs,它具有一个类型为ManagementBaseObject的NewEvent属性。这没有一个InvokeMethod方法。我可以将NewEvent属性转换为ManagementObject吗?或者我需要重新查询并创建ManagementObject?下面的代码很好用,但不想重新查询。将.Net ManagementBaseObject转换为ManagementObject
Imports System.Management
Public NotInheritable Class EntryPoint
Public Shared Sub Main(ByVal args() As String)
Dim scope As New ManagementScope("\\.\root\cimV2")
Dim query As New WqlEventQuery("__InstanceCreationEvent", TimeSpan.FromSeconds(1), "TargetInstance isa ""Win32_Process""")
Using watcher As New ManagementEventWatcher(scope, query)
AddHandler watcher.EventArrived, AddressOf EventArrived
watcher.Start()
Console.WriteLine("Waiting for processes to start...")
Console.ReadLine()
watcher.Stop()
End Using
End Sub
Private Shared Sub EventArrived(ByVal sender As Object, ByVal e As EventArrivedEventArgs)
Dim targetInstance As ManagementBaseObject = e.NewEvent("TargetInstance")
Dim process As New ManagementObject("win32_process.handle=" + targetInstance("ProcessId").ToString())
Dim output(1) As String
process.InvokeMethod("GetOwner", output)
Console.WriteLine("Process {0} started by {2}\{1}", targetInstance("Name"), output(0), output(1))
End Sub
End Class
答
IS的对象ManagementObject
实例?索引器可以将返回值作为Base
传递,因为它是通用属性。试试这个:
Private Shared Sub EventArrived(ByVal sender As Object, ByVal e As EventArrivedEventArgs)
Dim targetInstance As ManagementBaseObject = e.NewEvent("TargetInstance")
If TypeOf targetInstance Is ManagementObject Then
Dim mo as ManagementObject = DirectCast(targetInstance, ManagementObject)
Dim output(1) as String
mo.InvokeMethod("GetOwner", output)
Console.WriteLine("Process {0} started by {2}\{1}", targetInstance("Name"), output(0), output(1))
End If
End Sub
否go ... targetInstance不是一个ManagementObject实例。 – 2009-06-22 19:31:28
在这种情况下,不,不可能不执行另一个查询。 – 2009-06-23 02:17:18