我想检索当前进程(或特定进程)的cpu和ram使用情况。 检索窗口的标题不是问题,而且该部分有效。但即使活动窗口以70%或更高的CPU运行,cpu显示仍保持在0%。
(INT)pCPU.NextValue(); //<<<<不断返回0 ...
注意:我想用性能计数器来做。我不想使用Process变量来执行它,因为那可能会引发“权限错误不足”。
[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
}
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
}
答案 0 :(得分:0)
请勿直接使用该值,请使用计算出的样本
CounterSample sample1 = pCPU.NextSample();
float value = CounterSample.Calculate(sample1);
如果您的计数器是'费率'类型样本,那么您需要获得两个样本,
CounterSample sample1 = counter.NextSample();
Thread.Sleep(1000); // wait some time
CounterSample sample2 = counter.NextSample();
float value = CounterSample.Calculate(sample1, sample2);