C#读取用户输入而不停止应用 [英] c# reading user input without stopping an app

查看:254
本文介绍了C#读取用户输入而不停止应用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

结果
我知道我可以使用ReadKey为该但直到用户按下一个键将冻结的应用程序。是否有可能(在控制台应用程序)有一定的循环运行,仍然能够反应?我只能想到的事件,但不知道如何在控制台中使用它们。
我的想法是,循环将每次迭代过程中检查输入。


I know I can use ReadKey for that but it will freeze the app until user presses a key. Is it possible (in console app) to have some loop running and still be able to react? I can only think of events but not sure how to use them in console. My idea was that the loop would check for input during each iteration.

推荐答案

他们的方式我这样做对我自己的应用程序是有一个专门的线程调用到 System.Console.ReadKey(真)并提出按键(以及任何其它事件)到消息队列。

They way I have done this for my own application was to have a dedicated thread that calls into System.Console.ReadKey(true) and puts the keys pressed (and any other events) into a message queue.

主线程然后服务该队列在循环中(以类似的方式,以在Win32应用程序主循环),确保​​渲染和事件处理上的所有处理单个线程。

The main thread then services this queue in a loop (in a similar fashion to the main loop in a Win32 application), ensuring that rendering and event processing is all handled on a single thread.

private void StartKeyboardListener()
{
    var thread = new Thread(() => {
                                      while (!this.stopping)
                                      {
                                          ConsoleKeyInfo key = System.Console.ReadKey(true);
                                          this.messageQueue.Enqueue(new KeyboardMessage(key));
                                      }
                                  });

    thread.IsBackground = true;
    thread.Start();
}

private void MessageLoop()
{
    while (!this.stopping)
    {
        Message message = this.messageQueue.Dequeue(DEQUEUE_TIMEOUT);

        if (message != null)
        {
            switch (message.MessageType)
            {
                case MessageType.Keyboard:
                    HandleKeyboardMessage((KeyboardMessage) message);
                    break;
                ...
            }
        }

        Thread.Yield(); // or Thread.Sleep(0)
    }
}

这篇关于C#读取用户输入而不停止应用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆