我正在尝试使用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();
}
}
}
}发布于 2012-07-25 14:05:52
这是因为你有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()阻塞在您的代码中。我没有检查您是否需要readkey的参数true,这是由您来找出的
https://stackoverflow.com/questions/11643456
复制相似问题