C# - 在控制台应用程序执行期间捕获空格键

时间:2011-03-02 20:04:06

标签: c# console-application capture keyboard-events

有没有办法在控制台应用程序中运行进程,并且在执行期间,如果按下空格键,请使用应用程序的状态更新控制台?我们有一个解析文件以进行格式化的进程,并且在执行期间,状态不会更新。有没有办法在执行期间捕获键盘事件,类似于CTRL-C委托方法?

TL / DR:在运行过程中,使用空格键更新屏幕状态。

C#控制台应用程序。

1 个答案:

答案 0 :(得分:2)

确定,但是您需要一个后台线程来进行实际处理。基本上,只需让你的控制台进程在后台线程中启动你的文件解析,然后在它工作时,循环检查keypress和Thread.Yield()语句。如果按下某个键,则从后台线程正在更新的某个类中获取状态更新:

private static StatusObject Status;

public static void main(params string[] args)
{
   var thread = new Thread(PerformProcessing);
   Status = new StatusObject();
   thread.Start(Status);

   while(thread.IsAlive)
   {
      if(keyAvailable)
         if(Console.ReadKey() == ' ')
            ShowStatus(Status);

      //This is necessary to ensure that this main thread doesn't monopolize
      //the CPU going through this loop; let the background thread work a while
      Thread.Yield();
   }

   thread.Join();
}

public void PerformProcessing(StatusObject status)
{
   //do your file parsing, and at significant stages of the process (files, lines, etc)
   //update the StatusObject with vital info. You will need to obtain a lock.
}

public static void ShowStatus(StatusObject status)
{
   //lock the StatusObject, get the information from it, and show it in the console.
}