2012-01-09 41 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); 
    }