[英]C# Console.ReadKey 1 character lag?
我试图使用Console.ReadKey()函数来拦截用户的击键并重建他们在屏幕上键入的内容(因为我需要经常清除屏幕,经常移动光标,这似乎就像最完整的方法一样,以确保输入的内容不会消失或不会出现在整个屏幕上的随机点上。
我的问题是:在做类似的事情时,是否有人因缺乏更好的用语而经历过1个字符的“滞后”? 假设我要输入单词“ This”。 当我按“ T”时,无论等待多长时间,都不会显示任何内容。 当我按“ h”时,出现“ T”。 “ i”,出现“ h”。 我键入的字母直到我按下另一个键时才会出现,即使该键是空格键。 有人对我做错了什么建议吗? 我确定这与我使用Console.Readkey的方式有关,我只是看不到有什么替代方法会起作用。 我在下面附上了一个小而简单的示例。
谢谢!
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
namespace ConsoleApplication2
{
class Program
{
private static string userInput = "";
static ConsoleKeyInfo inf;
static StringBuilder input = new StringBuilder();
static void Main(string[] args)
{
Thread tickThread = new Thread(new ThreadStart(DrawScreen));
Thread userThread = new Thread(new ThreadStart(UserEventHandler));
tickThread.Start();
Thread.Sleep(1);
userThread.Start();
Thread.Sleep(20000);
tickThread.Abort();
userThread.Abort();
}
private static void DrawScreen()
{
while (true)
{
Console.Clear();
Console.SetCursorPosition(0, 0);
Console.Write("> " + userInput);
Thread.Sleep(300);
}
}
private static void UserEventHandler()
{
inf = Console.ReadKey(true);
while (true)
{
if (inf.Key != ConsoleKey.Enter)
input.Append(inf.KeyChar);
else
{
input = new StringBuilder();
userInput = "";
}
inf = Console.ReadKey(true);
userInput = input.ToString();
}
}
}
}
这是因为您有2次Console.ReadKey()
如果您将代码更改为此
private static void UserEventHandler()
{
while (true)
{
inf = Console.ReadKey(true);
if (inf.Key != ConsoleKey.Enter)
input.Append(inf.KeyChar);
else
{
input = new StringBuilder();
userInput = "";
}
userInput = input.ToString();
}
}
它不会滞后。 第二个Console.ReadKey()
阻塞了您的代码。 我没有检查您是否需要true
的参数,这是供您查找的
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.