我正在尝试使用以下代码来写出在计算机上启动的所有进程。我的问题是EventArrived方法传递一个EventArrivedEventArgs,它具有类型为ManagementBaseObject的NewEvent属性。这没有InvokeMethod方法。我可以将NewEvent属性转换为ManagementObject的一些方式,还是需要重新查询和创建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
答案 0 :(得分:2)
是对象a 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