首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >C# Console.ReadKey 1字符滞后?

C# Console.ReadKey 1字符滞后?
EN

Stack Overflow用户
提问于 2012-07-25 13:47:18
回答 1查看 1.1K关注 0票数 0

我正在尝试使用Console.ReadKey()函数来拦截用户的击键并重新构建他们在屏幕上键入的内容(因为我需要经常清除屏幕,经常移动光标,这似乎是确保他们键入的内容不会消失或出现在屏幕各处的最可靠的方法。

我的问题是:有没有其他人在做类似的事情时,因为缺乏更好的术语而经历过1个字符的“滞后”?假设我想输入单词"This“。当我按下"T“时,无论我等待多长时间,都不会显示任何内容。当我按"h“时,出现"T”。"i",则会出现"h“。我输入的字母不会出现,直到我按下另一个键,即使那个键是空格键。有没有人对我做错了什么有什么建议?我确信这与我使用Console.Readkey的方式有关,我只是看不出有什么替代方案可以工作。我在下面附上了一个简单的小例子。

谢谢!

代码语言:javascript
复制
    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();

            }
        }

    }
}
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2012-07-25 14:05:52

这是因为你有2倍的Console.ReadKey()

如果你把你的代码改成这样

代码语言:javascript
复制
    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,这是由您来找出的

票数 5
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/11643456

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档