[Windows Terminal] `Console.KeyAvailable` causes the next Unicode character input 'EN DASH' to be skipped in console
#38.966 aperta il 8 lug 2020
Metriche repository
- Star
- (17.886 star)
- Metriche merge PR
- (Merge medio 12g 11h) (661 PR mergiate in 30 g)
Descrizione
Description
When pasting text with Unicode character in it to console on Windows (conhost) using right click, the Unicode character, such as the 'EN DASH' character in the following example
New-StoragePool –FriendlyName
will somehow be skipped and missing from the Console.ReadKey(true) calls. More investigation shows the call to Console.KeyAvailable could be the culprit -- when Console.KeyAvailable is not in use, Console.ReadKey(true) is able to receive the 'EN DASH' character just fine.
Repro code
using System;
namespace console
{
public class Program
{
static void Main(string[] args)
{
do {
if (Console.KeyAvailable)
{
var key = Console.ReadKey(true);
Print(key);
}
else
{
var key = Console.ReadKey(true);
Print(key);
}
}
while(true);
}
// Print the decimal value of `KeyChar`, the `ConsoleKey` and `Modifiers` values.
private static void Print(ConsoleKeyInfo key)
{
Console.Write('[');
Console.Write((int)key.KeyChar);
Console.Write($" {key.Key} {key.Modifiers}");
Console.Write(']');
}
}
}
Copy the text "l –F", and then right click to paste the text, you will see that the 'EN DASH' character is missing:

Then, copy the text "–F" with the 'EN DASH' character being the first character, so Console.KeyAvailable will not run before accepting that character, then Console.Readkey(true) is able to receive that Unicode character ():

Additional information
Please note that, the same issue happens in .NET 5 preview as well.
If I change the Main method above to be the following, then Console.Readkey can always receive the Unicode character.
But I have to use Console.KeyAvailable in my project together with Console.ReadKey, and hence cannot receive the Unicode when user is pasting by right click in console.
static void Main(string[] args)
{
do
{
var key = Console.ReadKey(true);
Print(key);
}
while(true);
}