Skip to content

System.ConsoleKeyInfo can not handle Unicode surrogate pair and Emoji Sequences #27828

Open

Description

@WenceyWang

Windows have a soft keyboard that can type Emoji directly.

image

Emoji is a set of chars that cannot be stored in a single char while System.ConsoleKeyInfo uses a char to store the content of the pressed key.

public char KeyChar { get; }

In my test, System.Console.ReadKey will return a System.ConsoleKeyInfo which KeyChar is the first char of the emoji (a sequence of surrogate pair, might 10+) and I have no way to get the other chars.

The problem of ReadKey is it may return the first half of a surrogate pair and the next ReadKey call will return the next keypress, not the remaining part of the surrogate pair.

This makes rubbish out and impossible to work around in user code.

This problem also applies to these keyboards for script language.

Activity

  1. Clockwork-Muse commented on Nov 6, 2018

    @Clockwork-Muse
    Contributor

    ...this can't be unique to emoji, presumably? Shouldn't some upper-range characters and combining-characters suffer the same fate?

    Also, I'm assuming this would be triggered by copy/paste input, so I don't think it's just soft keyboards we have to worry about.

  2. transferred this issue fromdotnet/corefxon Jan 31, 2020
  3. added this to the Future milestone on Jan 31, 2020
  4. added
    untriaged
    on Feb 23, 2020
  5. carlossanlop commented on Apr 1, 2020

    @carlossanlop
    Contributor

    This is a problem with surrogate pairs in general. It's not clear how we would address this issue without introducing some form of a breaking change.

  6. removed
    untriaged
    on Apr 1, 2020
  7. Serentty commented on Jul 3, 2020

    @Serentty
    Contributor

    To me, it seems like the logical course of action would be to introduce a new API based around Rune instead of char, and gradually deprecate ReadKey() in favour of ReadRune(). The large existing code bases would mean it would probably never be able to be removed completely, but the deprecation strikethrough in Visual Studio could help encourage the use of that new API.

    Now that I think about it, it would probably also make sense to have a key-reading API that returns a string, since many languages such as Guarani use characters which one might input with a single keypress, and yet are composed of multiple code points. Having ReadRune() is more pressing though, I think. Not handling combining characters is a matter of functionality, but treating code points as 16-bit is just a matter of being outdated.

    However, both seem to be an issue for PSReadLine, which leads to a longstanding bug in PowerShell.

  8. BDisp commented on Nov 10, 2020

    @BDisp

    Is there a way to get surrogate pair from System.ConsoleKeyInfo. I'm only getting the first char. Or some method to get the next chars?

    Edit:
    Console.KeyAvailable is the answer. For surrogate pair we need to use Rune but sometimes I only have his length value after write and would be better to get it before.

  9. WenceyWang commented on Apr 11, 2021

    @WenceyWang
    Author

    To me, it seems like the logical course of action would be to introduce a new API based around Rune instead of char, and gradually deprecate ReadKey() in favour of ReadRune(). The large existing code bases would mean it would probably never be able to be removed completely, but the deprecation strikethrough in Visual Studio could help encourage the use of that new API.

    Now that I think about it, it would probably also make sense to have a key-reading API that returns a string, since many languages such as Guarani use characters which one might input with a single keypress, and yet are composed of multiple code points. Having ReadRune() is more pressing though, I think. Not handling combining characters is a matter of functionality, but treating code points as 16-bit is just a matter of being outdated.

    However, both seem to be an issue for PSReadLine, which leads to a longstanding bug in PowerShell.

    ReadKey is important for us. As there are many keys on a keyboard that are not directly mapped to Unicode characters and we do need to know if shift, ctrl, or alt key is pressed.

    The design of key code and key char is dated to the IBM PC keyboard controller. This is not the *nix way of letting the console device and program itself escape these keys presses and pass them as a stream.

    I think the proper way is to add a string or ReadOnlySpan typed property in System.ConsoleKeyInfo to contain all content caused by a key pressing, which will not break currently working code and let new code be aware of the Unicode keyboard.

  10. GrabYourPitchforks commented on Apr 12, 2021

    @GrabYourPitchforks
    Member

    I'm assuming the scenario is "I want to be able to get an entire grapheme cluster via ReadKey." (See this doc for the difference between char, Rune, and "grapheme cluster".) There are going to be a few complications with this scenario, regardless of the proposed API.

    If you return char or Rune, you may only be returning part of the information. As mentioned earlier, char by itself isn't sufficient to represent supplementary code points. And Rune by itself isn't sufficient to represent many Emoji, which often consist of a base character + extra modifiers like skin tone, gender, etc.

    An alternative solution might be to return string, but this runs into an interesting edge case. Say that I type an 'e' character, then I paste the accent modifier so that it is displayed as "é" (that's 2 chars!). What should the behavior here be? Should ReadKey return "e" by itself because that's what I typed first, then return "\u0301" on the second call because that's the accent modifier I pasted after typing 'e'? Similar situation to entering a base Emoji code point, then later entering a skin tone modifier. The second entry affects how the first one was intended to be displayed.

    Now, is this acceptable? Maybe your application doesn't interpret these as individual to-be-displayed characters and stitches them all together after the fact anyway. But if you're stitching them together, presumably you could stitch together char-by-char using the current API, and no string-by-string / Rune-by-Rune API is needed.

    This is one of those weird things where the requested change need to be laid out very specifically. Things that might seem obvious to one person might not seem obvious to another, and it could have a ripple effect which upends the proposed solution.

  11. WenceyWang commented on Apr 12, 2021

    @WenceyWang
    Author

    The problem of ReadKey is it may return the first half of a surrogate pair and drop the next char, this making rubbish out and impossible to workaround in user code.

    In short, I think we should at least let ReadKey somehow working correctly without breaking the current running code.

    I think it's OK to get "e" and then "\u0301" by ReadKey if they are inputted as two key presses.

    The problem is that we do need a keypress-by-keypress API. which makes programs able to respond to keypresses instead of char-based stream input. This is the way we handle console input on Windows. https://docs.microsoft.com/en-us/windows/console/readconsoleinput will return us an array of key press or mouse click events instead of char stream.

    Use Console.Read cannot read key code or modifier key status etc. We can not rely on escape sequence.

    I have submitted my API suggestion at #51085 which I think makes sense for us.

  12. WenceyWang commented on Apr 12, 2021

    @WenceyWang
    Author

    @DHowett I think the problem is rooted at https://docs.microsoft.com/en-us/windows/console/key-event-record-str which uses a WCHAR to store translated Unicode character which for now the input can be a surrogate pair or sequence of Unicode codepoint.

  13. changed the title [-]System.ConsoleKeyInfo can not handle Emoji key on soft keyboard[/-] [+]System.ConsoleKeyInfo can not handle Unicode surrogate pair and Emoji Sequences[/+] on Apr 12, 2021
  14. DHowett commented on Apr 12, 2021

    @DHowett

    Other applications seem capable of handling surrogate pairs in the WCHAR-typed field of two KEY_EVENT_RECORDs just fine.

  15. BDisp commented on Apr 12, 2021

    @BDisp

    @DHowett that it's true as we can handling any surrogate pairs of two or more KEY_EVENT_RECORDs, but how to deal when the same unicode code returns different string length with other font types?

  16. DHowett commented on Apr 12, 2021

    @DHowett

    The font cannot change the length of a string.

    If you're talking about the column count (perceived space taken up by the string of printed to a console), that's just off topic for this issue :). That's also one of the harder issues in terminal emulation.

  17. GrabYourPitchforks commented on Apr 13, 2021

    @GrabYourPitchforks
    Member

    If you really want your mind to melt, spec out what behavior your app will have when the user hits BACKSPACE immediately after entering a complex multi-scalar emoji. :)

  18. WenceyWang commented on Apr 13, 2021

    @WenceyWang
    Author

    Let me repeat the issue again:

    The problem of ReadKey is it may return the first half of a surrogate pair and the next ReadKey call will return the next keypress, not the remaining part of the surrogate pair.

    This makes rubbish out and impossible to work around in user code.

  19. BDisp commented on Apr 13, 2021

    @BDisp

    @WenceyWang you may need to deal with escape sequences to get all the bytes needed for the surrogate pair.

  20. added
    backlog-cleanup-candidate
    on Oct 14, 2025
  21. WenceyWang commented on Oct 14, 2025

    @WenceyWang
    Author

    Due to lack of recent activity, this issue has been marked as a candidate for backlog cleanup. It will be closed if no further activity occurs within 14 more days. Any new comment (by anyone, not necessarily the author) will undo this process.

    This process is part of our issue cleanup automation.

    A bug won't automatically disappear. Closing a genuine, years-old, unfixed issue won't help.

  22. removed
    backlog-cleanup-candidate
    on Oct 14, 2025
  23. BDisp commented on Oct 14, 2025

    @BDisp

    Emoji is a set of chars that cannot be stored in a single char while System.ConsoleKeyInfo uses a char to store the content of the pressed key.

    public char KeyChar { get; }

    This is the expected behavior and also valid for any input terminal in Windows, Linux and macOS.

    In my test, System.Console.ReadKey will return a System.ConsoleKeyInfo which KeyChar is the first char of the emoji (a sequence of surrogate pair, might 10+) and I have no way to get the other chars.

    The problem of ReadKey is it may return the first half of a surrogate pair and the next ReadKey call will return the next keypress, not the remaining part of the surrogate pair.

    I don't know if it was an issue before but actually It's working as expected related to this issue. The main key which it's necessary to set is Console.OutputEncoding = Encoding.UTF8;. at the beginning of the code.

    This makes rubbish out and impossible to work around in user code.

    That depends of the intercept parameter value passed to the Console.ReadKey method. If it's true then the developer must handle the output and if it's false the output is automatic and the developer only need to handle if i's needed.

    This problem also applies to these keyboards for script language.

    To have full control about the input coming in, especially with VTS (Virtual Terminal Sequences) enabled, the Console.ReadKey method must always return the KeyChar, at least if the intercept parameter is true, instead of decoding some escape sequences incorrectly. But this is another issue not related to this one.

    To prove that this issue isn't an issue anymore in my opinion, I add the follow C# code using the Console.ReadKey method testing the intercept parameter as true or false:

    using System.Text;
    
    Console.OutputEncoding = Encoding.UTF8;
    
    Console.WriteLine("By default the intercept parameter is true to not display the pressed key.");
    Console.WriteLine("To not intercept and to display the pressed key, press 'f/F'.");
    Console.Write("Otherwise press any key to continue.");
    
    var intercept = true;
    var key = Console.Read();
    if ((char)key == 'f' || (char)key == 'F')
    {
        intercept = false;
    }
    
    Console.WriteLine("Open emojis on Windows by press the Windows key + . (period)");
    
    char? highSurrogate = null;
    
    while (true)
    {
        var input = Console.ReadKey(intercept);
        if (input.Key == ConsoleKey.Escape)
        {
            break;
        }
    
        if (input.Key == ConsoleKey.Enter)
        {
            Console.Write($"{Environment.NewLine}");
        }
    
        if (!intercept)
        {
            continue;
        }
    
        if (char.IsHighSurrogate(input.KeyChar))
        {
            highSurrogate = input.KeyChar;
            continue;
        }
    
        if (char.IsLowSurrogate(input.KeyChar))
        {
            if (highSurrogate is not null)
            {
                Console.Write($"{(char)highSurrogate}{input.KeyChar}");
                highSurrogate = null;
                continue;
            }
        }
    
        if (input.Key != ConsoleKey.NoName)
        {
            Console.Write($"{input.KeyChar}");
        }
    }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions