I am trying to get the CPU time like in the task manager but the values and processes i am getting are not matching what is displayed in the task manager.
This is the code i am using,
Public Shared Function getAllProcesses() As List(Of ServProcess)
Dim procLST As New List(Of ServProcess)
Dim ProcID As Integer
Dim ret As New ServProcess
Try
Dim MyobjectQuery As New System.Management.ObjectQuery("select * from Win32_Process")
Dim MySearcher As New System.Management.ManagementObjectSearcher(MyobjectQuery)
For Each Mgmt As System.Management.ManagementObject In MySearcher.Get()
Dim m_Process As New ServProcess
m_Process.Name = Mgmt("Name")
ProcID = Mgmt("ProcessID")
If ProcID <> 0 Then
ret = GetUssage(ProcID)
m_Process.ProcessTime = ret.ProcessTime
m_Process.CpuVal = ret.CpuVal
If m_Process.ProcessTime IsNot Nothing And m_Process.Name IsNot Nothing And m_Process.CpuVal IsNot Nothing Then
If m_Process.ProcessTime <> "" Then
procLST.Add(m_Process)
End If
End If
End If
Next
Catch ex As Exception
End Try
Return procLST
End Function
Public Shared Function GetUssage(ByVal pid As String) As ServProcess
Dim MyobjectQuery As New System.Management.ObjectQuery("select * from Win32_Process WHERE ProcessID = " + pid)
Dim MySearcher As New System.Management.ManagementObjectSearcher(MyobjectQuery)
Dim ProcessorUsage As Decimal
Dim msPassed As Decimal
Dim ret As New ServProcess
For Each Mgmt As System.Management.ManagementObject In MySearcher.Get()
Dim currentTime As DateTime = DateTime.Now
Try
Dim firstSample, secondSample As DateTime
Dim ProcessorTime As String
firstSample = DateTime.Now
Mgmt.Get()
Dim u_OldCPU As Long = CType(Mgmt.Properties("UserModeTime").Value, ULong) + CType(Mgmt.Properties("KernelModeTime").Value, ULong)
secondSample = DateTime.Now
Mgmt.Get()
Dim u_newCPU As ULong = CType(Mgmt.Properties("UserModeTime").Value, ULong) + CType(Mgmt.Properties("KernelModeTime").Value, ULong)
msPassed = CType((secondSample - firstSample).TotalMilliseconds, Decimal)
ProcessorUsage = CType(u_newCPU - u_OldCPU, Decimal) / (msPassed * 100 * Environment.ProcessorCount)
Dim mDate As DateTime = CDate(Mid(Mgmt("CreationDate"), 5, 2) & "/" & Mid(Mgmt("CreationDate"), 7, 2) & "/" & Left(Mgmt("CreationDate"), 4) & " " & Mid(Mgmt("CreationDate"), 9, 2) & ":" & Mid(Mgmt("CreationDate"), 11, 2) & ":" & Mid(Mgmt("CreationDate"), 13, 2))
Dim ProcessorSpan As TimeSpan = currentTime.Subtract(mDate)
ProcessorTime = ProcessorSpan.Days.ToString("000") & ":" & ProcessorSpan.Hours.ToString("00") & ":" & ProcessorSpan.Minutes.ToString("00")
ret.Name = ""
ret.CpuVal = ProcessorUsage.ToString("0.00")
ret.ProcessTime = ProcessorTime
Catch ex As Exception
End Try
Next
Return ret
End Function
I am not sure if i am going about this the wrong way or if there is a better more efficient way to do this.
So I guess my question is what is the best way to get these values to display them in a datagrid view in a windows form.
thanks