How do I get the char for a keypress knowing only the ConsoleKey enum and Modifiers?


I want to create a ConsoleKeyInfo instance of the matching closing brace of any open brace typed in a PowerShell session (I’m using PSReadline to do the key handling). For your convenience, here are the properties of all the keys involved

In the key handler, I am given the ConsoleKeyInfo for the “chord” that was pressed (and PSReadline does filtering, so I already know I’m receiving only an Oem4 or Shift+Oem4). I want to generate the matching ConsoleKeyInfo so I can send the pair printing to the console.

The ConsoleKeyInfo constructor takes

  • a char
  • a System.ConsoleKey
  • a bool each for Shift, Alt, and Control

I can get the correct ConsoleKey by casting it to an int and moving up two…

And I can map from the pressed key’s Modifiers by testing it bitwise…

But, I have no idea how to get the literal char for this console key. How does the console get the char from the keyboard key? Can this only be done with a live console/keyboard?

I’d rather not maintain a map of the key pairs nor split the handlers, one for each “chord”, and hardcode the matching key char. 🙁


You probably don’t need to create a ConsoleKeyInfo just for PSReadline.

Occasionally you may need to pass a ConsoleKeyInfo to a method in PSConsoleReadLine, but most methods in PSConsoleReadLine that accept a ConsoleKeyInfo don’t even look at the argument. That’s why the parameter is Nullable.

This doesn’t actually answer your question though. JaredPar is absolutely correct that in general, it’s not possible to convert a ConsoleKey/ConsoleModifiers pair to a char. If we don’t care about full generality (and currently PSReadline doesn’t), you can use code similar to what PSReadline uses:


How do I get the char for a keypress knowing only the ConsoleKey enum and Modifiers? by licensed under CC BY-SA | With most appropriate answer!

Leave a Reply