我正在创建一个监控计算机使用情况的程序。该程序的一部分要求我始终知道前景窗口是什么。这是通过以下代码实现的:
// 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,因为它是在每秒滴答的代码中调用的。程序中的核心功能需要每秒滴答作响。
那么我的问题是,有没有办法在不让我的程序冻结计算机的情况下解决这个问题?
感谢您的时间和回复!