c# reading user input without stopping an app(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#在不停止应用程序的情况下读取用户输入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:c#在不停止应用程序的情况下读取用户输入
基础教程推荐
- MS Visual Studio .NET 的替代品 2022-01-01
- 有没有办法忽略 2GB 文件上传的 maxRequestLength 限制? 2022-01-01
- 如何激活MC67中的红灯 2022-01-01
- 为什么Flurl.Http DownloadFileAsync/Http客户端GetAsync需要 2022-09-30
- 将 Office 安装到 Windows 容器 (servercore:ltsc2019) 失败,错误代码为 17002 2022-01-01
- c# Math.Sqrt 实现 2022-01-01
- SSE 浮点算术是否可重现? 2022-01-01
- 将 XML 转换为通用列表 2022-01-01
- rabbitmq 的 REST API 2022-01-01
- 如何在 IDE 中获取 Xamarin Studio C# 输出? 2022-01-01