【发布时间】:2011-03-23 22:08:54
【问题描述】:
我正在创建一个监控计算机使用情况的程序。该程序的一部分要求我始终知道前景窗口是什么。这是通过这段代码实现的:
// Returns the name of the process owning the foreground window.
private static Process GetForegroundProcess()
{
try
{
IntPtr hwnd = GetForegroundWindow();
// The foreground window can be NULL in certain circumstances,
// such as when a window is losing activation.
uint pid;
GetWindowThreadProcessId(hwnd, out pid);
Process p = Process.GetProcessById((int)pid);
return p;
}
catch (Exception)
{
return null;
}
}
我遇到的问题是 CPU 消耗。这逐渐使用了我所有的 CPU,因为它是在每秒滴答的代码中调用的。程序中的核心功能需要每秒滴答作响。
然后我的问题是,有没有办法在不让我的程序冻结计算机的情况下解决这个问题?
感谢您的宝贵时间和回复!
【问题讨论】:
-
这没有意义。每秒计时一次然后调用该代码的计时器不会使用 100% 的 CPU。还有其他问题。
-
您在处理完这些
Process对象后是否对它们调用Dispose?
标签: c# timer monitor cpu-usage foreground