Quantcast
Channel: VBForums - CodeBank - Visual Basic 6 and earlier
Viewing all articles
Browse latest Browse all 1476

VB6 gets the CPU utilization of the specified process.

$
0
0
Dim C As Currency
C = CPUUSage(GetPidByHwnd(Me.hWnd))
MSGBOX C & "%"

Code:

Function GetPidByHwnd(hWnd As Long, Optional lThread As Long)
    lThread = GetWindowThreadProcessId(hWnd, GetPidByHwnd)
 End Function

Function CPUUSage(ProcID As Long) As Currency
 On Error Resume Next
 Dim n1, d1
 Dim n2, d2, nd, dd
    Dim objService, objInstance1
    Dim perf_instance2
    Dim PercentProcessorTime
 Set objService = GetObject("Winmgmts:{impersonationlevel=impersonate}!\Root\Cimv2")
   
 For Each objInstance1 In objService.ExecQuery("Select * from Win32_PerfRawData_PerfProc_Process where IDProcess = '" & ProcID & "'")
  n1 = objInstance1.PercentProcessorTime
  d1 = objInstance1.TimeStamp_Sys100NS
  Exit For
 Next

 For Each perf_instance2 In objService.ExecQuery("Select * from Win32_PerfRawData_PerfProc_Process where IDProcess = '" & ProcID & "'")
  n2 = perf_instance2.PercentProcessorTime
  d2 = perf_instance2.TimeStamp_Sys100NS
  Exit For
 Next
 ' CounterType - PERF_100NSEC_TIMER_INV
 ' Formula - (1- ((N2 - N1) / (D2 - D1))) x 100
 nd = (n2 - n1)
 dd = (d2 - d1)
 PercentProcessorTime = ((nd / dd)) * 100
     
 CPUUSage = Round(PercentProcessorTime, 2)
End Function


Viewing all articles
Browse latest Browse all 1476


<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>