I would like to retrieve the cpu and ram usage at that point for the foreground process (or a specific one).
Retrieving the window’s title is not a problem and that part works. But the cpu display stays at 0% even when the active window is running at 70% cpu or more.
(int)pCPU.NextValue(); // <<<< keeps returning 0…
Note: I want to do it with a performance counter. I don’t want to do it using the Process variable because that one might raise ‘insufficient privilege errors’.
[DllImport("user32.dll")]
static extern IntPtr GetForegroundWindow();
[DllImport("user32.dll")]
static extern int GetWindowText(IntPtr hWnd, StringBuilder text, int count);
[DllImport("user32.dll")]
public static extern IntPtr GetWindowThreadProcessId(IntPtr hWnd, out uint ProcessId);
public void GetActiveCPUAndRam(out string windowTitle, out int CPUUsagePerc, out int RAMUsage)
{
IntPtr hwnd = GetForegroundWindow();
uint pid;
GetWindowThreadProcessId(hwnd, out pid);
Process activeProc = Process.GetProcessById((int) pid);
#region Window Title
const int nChars = 256;
StringBuilder Buff = new StringBuilder(nChars);
if (GetWindowText(hwnd, Buff, nChars) > 0)
windowTitle = Buff.ToString();
else
{
windowTitle = "";
CPUUsagePerc = 0;
RAMUsage = 0;
return;
}
#endregion
#region RAM/CPU
PerformanceCounter pCPU = new PerformanceCounter("Process", "% Processor Time", activeProc.ProcessName, true);
pCPU.NextValue();
CPUUsagePerc = (int)pCPU.NextValue(); // <<<<< problem here.
RAMUsage = 0; // TODO:
#endregion
}
EDIT:
I tried the new solution:
But when I run a cpu stress test program that pushes the cpu usage to 100% (single core) . Then the solution below shows that the cpu usage of that process is like 300-400% of the total cpu… Obviously something is still wrong.
private PerformanceCounter pCPU = null;
private IntPtr PreviousProcHwnd = IntPtr.Zero;
private CounterSample PreviousCPUCounterSample = CounterSample.Empty;
public void GetActiveCPUAndRam(out string windowTitle, out int CPUUsagePerc, out int RAMUsage)
{
...
#region RAM/CPU
if (PreviousProcHwnd != hwnd)
{
PreviousProcHwnd = hwnd;
pCPU = new PerformanceCounter("Process", "% Processor Time", activeProc.ProcessName,
true);
PreviousCPUCounterSample = CounterSample.Empty;
}
CounterSample sample1 = pCPU.NextSample();
CPUUsagePerc = (int)CounterSample.Calculate(PreviousCPUCounterSample, sample1);
PreviousCPUCounterSample = sample1;
RAMUsage = 0; // TODO:
#endregion
}
Do not use the value directly, use the calculated sample,
if your counter is a ‘rate’ type sample, then you will need to get two samples,