I'm creating a program that should monitor all the child processes after a initial one.
I'm doing this with ProcessExtensions.GetProcess function from process extensions, such as:
Dim counter
counter = 0
Dim pr2 = ProcessExtensions.GetProcesses.ToList()
Console.WriteLine(pr2.Count)
For Each pr3 As Process In pr2
counter = counter + 1
Dim parentpr As Process = ProcessExtensions.Parent(pr3) '' <- problem right here
If parentpr IsNot Nothing Then
Console.WriteLine(counter & " " & pr3.Id & " " & pr3.ProcessName & " " & pr3.StartTime & " " & parentpr.Id)
End If
Next
Console.ReadKey()
The problem is, this is too slow, it takes around half a second to check each process on windows 10, and with over 200 processes on average it doesn't allow me to check if a child process was started effectively.
I've considered creating a filter with a start date, but that filter will loop trough all the processes as well, and will not provide a result fast enough.
Meanwhile tasklist
, or wmic process get
on a command line provide instant results, but will force me to re-write all the code.
Is it possible to monitor when a process start on windows 10, instantly?
Other ideas are also welcomed.
I'm new to VB, thanks in advance for any help.
Edit: The problem is getting the ParentID. I'm using a custom ProcessExtensions module that gets it, but its a bit slow.
Public NotInheritable Class ProcessExtensions
Inherits Process
Public Sub New()
End Sub
Private Shared Function FindIndexedProcessName(ByVal pid As Integer) As String
Try
Dim processName = Process.GetProcessById(pid).ProcessName
Dim processesByName = Process.GetProcessesByName(processName)
Dim processIndexdName As String = Nothing
For index As Integer = 0 To processesByName.Length - 1
processIndexdName = If(index = 0, processName, Convert.ToString(processName) & "#" & index)
Dim processId = New PerformanceCounter("Process", "ID Process", processIndexdName)
If CInt(processId.NextValue()).Equals(pid) Then
Return processIndexdName
End If
Next
Return processIndexdName
Catch ex As ArgumentException
Return Nothing
End Try
End Function
Private Shared Function FindPidFromIndexedProcessName(ByVal indexedProcessName As String) As Process
Dim parentId = New PerformanceCounter("Process", "Creating Process ID", indexedProcessName)
Try
Return Process.GetProcessById(CInt(parentId.NextValue()))
Catch ex As Exception
Return Nothing
End Try
End Function
Public Function Parent() As Process
Return FindPidFromIndexedProcessName(FindIndexedProcessName(Me.Id))
End Function
Public Shared Function Parent(ByVal pr As Process) As Process
Return FindPidFromIndexedProcessName(FindIndexedProcessName(pr.Id))
End Function
End Class