【问题标题】:C# - Capture spacebar press during console application executionC# - 在控制台应用程序执行期间捕获空格键
【发布时间】:2011-03-02 20:04:06
【问题描述】:

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

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

C# 控制台应用程序。

【问题讨论】:

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


    【解决方案1】:

    当然可以,但是您需要一个后台线程来进行实际处理。基本上,只需让您的控制台进程在后台线程中启动文件解析,然后在它工作时,循环检查按键和 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.
    }
    

    【讨论】:

    • 非常感谢!我将不得不更多地了解线程是如何工作的,但这是一个好的开始。再次感谢您的帮助。
    猜你喜欢
    • 1970-01-01
    • 2014-02-16
    • 2020-12-05
    • 2011-06-24
    • 2012-03-17
    • 1970-01-01
    • 2015-06-07
    • 2010-09-16
    相关资源
    最近更新 更多