dotnet/runtime

[Windows Terminal] `Console.KeyAvailable` causes the next Unicode character input 'EN DASH' to be skipped in console

Open

#38,966 opened on 2020年7月8日

GitHub で見る
 (13 comments) (2 reactions) (0 assignees)C# (5,445 forks)batch import
area-System.Consolehelp wanted

Repository metrics

Stars
 (17,886 stars)
PR merge metrics
 (平均マージ 12d 11h) (30d で 661 merged PRs)

説明

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:

image

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 ():

image

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);
        }

コントリビューターガイド