Convert .Net ManagementBaseObject to ManagementObject
Question
I am trying to use the following code to write out all processes started on a computer. My problem is that the EventArrived method is passed a EventArrivedEventArgs which has a NewEvent property of type ManagementBaseObject. This does not have a InvokeMethod method. Can I convert the NewEvent property to a ManagementObject some how, or do I need to requery and create a ManagementObject? The code below works great, but would like to not requery.
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
Solution
IS the object a ManagementObject
instance? The indexer may pass the return value as a Base
because it's a general-purpose property. Try this:
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
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow