进程是否实时运行



是否可以实时跟踪过程?例如,我有一个与游戏关联的应用程序。如果游戏正在运行,则按钮工作,如果游戏关闭,则按钮等待游戏启动。如何实现这一点?我找到了这个代码,但我的代码不是很好:)

while (true)
{
     System.Diagnostics.Process[] procs = 
     System.Diagnostics.Process.GetProcessesByName("notepad");
     if (procs.Count() == 0)
          break;
}

您包含的代码段可以工作,但它非常耗费资源,并且还会阻止执行线程。可以使用计时器事件来检查进程状态。

Timer myTimer = new Timer();
myTimer.Elapsed += new ElapsedEventHandler(DisplayTimeEvent);
myTimer.Interval = 1000; // 1000 ms is one second
myTimer.Start();
public static void DisplayTimeEvent(object source, ElapsedEventArgs e)
{
     System.Diagnostics.Process[] procs = 
         System.Diagnostics.Process.GetProcessesByName("notepad");
     //isButtonEnabled is needed to be defined on the upper context
     isButtonEnabled = procs.Count() != 0
}

最新更新