ユーザーのキーストロークをインターセプトし、画面に入力しているものを再構築するために、 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();
}
}
}
}