c#在不停止应用程序的情况下读取用户输入

c# reading user input without stopping an app(c#在不停止应用程序的情况下读取用户输入)
本文介绍了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(true) 并将按下的键(和任何其他事件)放入消息队列中.

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#在不停止应用程序的情况下读取用户输入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

DispatcherQueue null when trying to update Ui property in ViewModel(尝试更新ViewModel中的Ui属性时DispatcherQueue为空)
Drawing over all windows on multiple monitors(在多个监视器上绘制所有窗口)
Programmatically show the desktop(以编程方式显示桌面)
c# Generic Setlt;Tgt; implementation to access objects by type(按类型访问对象的C#泛型集实现)
InvalidOperationException When using Context Injection in ASP.Net Core(在ASP.NET核心中使用上下文注入时发生InvalidOperationException)
LINQ many-to-many relationship, how to write a correct WHERE clause?(LINQ多对多关系,如何写一个正确的WHERE子句?)