2012-01-09 19 views
3

有什么方法同时检测的ReadLine和ReadKey,因此,在大多数情况下,它表现为一个readline的,除应检测一些特殊的键输入?使用的Readline()和ReadKey()同时

我需要一些“水货”实施引进同时发生。 下面的代码是同步的,不符合我的需要

while ((line = Console.ReadLine()) != "x") 
{  
    if (line == "BLABLA") 
    { 
     //Stuff 
    } 

    else 
    { 
     //Stuff 
    } 

    ConsoleKeyInfo ki = Console.ReadKey(true); 
    if ((ki.Key == ConsoleKey.V) && (ki.Modifiers == ConsoleModifiers.Control)) 
    { 
     //Stuff 
    } 
} 
+0

可能重复http://stackoverflow.com/questions/5891538/c-sharp-listen-for-key-press-in-console-app – Alex 2012-01-09 14:45:05

回答

1

不,不是这样。两种方法都会阻止,直到用户在控制台上输入内容。所以,即使你能找到一条既平行运行的方法,也不会确定哪一方得到第一枪。

有一个(不显着)类似的问题:如何让Console.ReadLine()中止/中断,而无需用户输入一定量的时间之后。

已经有这个问题就在这里多次尝试:

大多数都是围绕或者创建自己的一个ReadLine功能,增加了超时的版本为蓝本(或在你的情况下对特定字符(代码)进行特殊处理)或使用某种线程。

两种方式要么是不平凡的或有自己的问题(请务必查看评论,甚至对接受的答案)。

总之,我认为您需要根据Console.ReadKey推出您自己的ReadLine版本,包含您的特殊处理以及您需要的大量真正的Console.ReadLine行为。请注意,这甚至还包括这些基本的东西返回,箭头键,退格处理等

更新:还有就是getline.cs代码从Mono project,就像是一些古老的UNIX提供了实现在线编辑功能炮弹(EMACS模式,如果你在意)。为此,我相信它需要实现某种ReadLine替换,尽管我没有检查。也许你可以用它作为出发点。

+0

绝对不值得实现一体的综合性readline的逻辑。对于这样一个“小”功能来说太麻烦了。简直不敢相信它是不可能的,因为它是一个真正期望从shell获得的功能。此外,我真的没有明白这一点:在一定的时间后,中止readline与我的文章有什么关系? – 2012-01-09 14:39:14

+0

@MikaJacobi它还需要您以最初不需要的方式修改ReadLine。特别是,至少有一些实现也需要重写,你可以使用你的功能扩展。 – 2012-01-09 14:40:39

1

这是我刚才做的一个功能。

眼下它只能处理退格,回车键,Esc键,但它可以很容易地被修改,如果你认为他们需要处理其他键。

// returns null if user pressed Escape, or the contents of the line if they pressed Enter. 
    private static string ReadLineOrEsc() 
    { 
     string retString = ""; 

     int curIndex = 0; 
     do 
     { 
      ConsoleKeyInfo readKeyResult = Console.ReadKey(true); 

      // handle Esc 
      if (readKeyResult.Key == ConsoleKey.Escape) 
      { 
       Console.WriteLine(); 
       return null; 
      } 

      // handle Enter 
      if (readKeyResult.Key == ConsoleKey.Enter) 
      { 
       Console.WriteLine(); 
       return retString; 
      } 

      // handle backspace 
      if (readKeyResult.Key == ConsoleKey.Backspace) 
      { 
       if (curIndex > 0) 
       { 
        retString = retString.Remove(retString.Length - 1); 
        Console.Write(readKeyResult.KeyChar); 
        Console.Write(' '); 
        Console.Write(readKeyResult.KeyChar); 
        curIndex--; 
       } 
      } 
      else 
      // handle all other keypresses 
      { 
       retString += readKeyResult.KeyChar; 
       Console.Write(readKeyResult.KeyChar); 
       curIndex++; 
      } 
     } 
     while (true); 
    }