【问题标题】:Key Listner in a console application using multithreading使用多线程的控制台应用程序中的键侦听器
【发布时间】:2017-04-15 05:49:07
【问题描述】:

我必须创建这个基于控制台的应用程序,但我遇到了这个问题: 我使用多线程创建了类似 KeyListener 的东西(不能做简单的循环,因为有第二个线程同时运行)。 并且线程中的循环需要检查按下的键是否为整数。

什么是我不明白的?

我得到这个的方式:线程中有一个无限循环,它试图捕获输入,如果input == 1 它在控制台中写入文本。 我错过了什么?

static void KeyRead()
{            
    do
    {
        int i = (int) Console.ReadKey().KeyChar;
        if (i == 1) {
           Console.Out.Write("Key 1 pressed");
        }
    } while (true);
}

static void Main(string[] args)
{
    Thread keyListner = new Thread(new ThreadStart(KeyRead));
    keyListner.Start();                   
}

【问题讨论】:

  • "什么是我不明白的?" -- 你的问题是什么? 具体是什么代码在做你不希望它做而你不知道如何修复?
  • 它基本上什么都不做。那就是问题所在。就像没有“if”语句一样。应该怎么做才能让它在 if 语句之后执行代码?我启动应用程序,按“1”并没有任何反应,尽管它应该写“按下键 1”。
  • 即使没有线程,您的程序也无法运行。 stackoverflow.com/questions/28955029/…

标签: c#


【解决方案1】:

KeyChar 返回 char 类型的值并将 char 转换为 int 返回表示该字符的 unicode 值。但是字符 '1' 有 unicode value 49,而不是 1。所以你必须修改条件来比较 i 等于 49 而不是 1。

static void KeyRead()
{
    do
    {
        int i = (int)Console.ReadKey().KeyChar;
        if (i == 49)
        {
            Console.Out.Write("Key 1 pressed");
        }
    } while (true);
}

但最好完全避免这种整数转换并直接比较字符:

static void KeyRead()
{
    do
    {
        char c = Console.ReadKey().KeyChar;
        if (c == '1')
        {
            Console.Out.Write("Key 1 pressed");
        }
    } while (true);
}

【讨论】:

    猜你喜欢
    • 2014-09-10
    • 2017-01-07
    • 1970-01-01
    • 1970-01-01
    • 2023-03-14
    • 2017-05-31
    • 1970-01-01
    相关资源
    最近更新 更多