Generic Read Key Method in C#

Pablo

Well-known member
Joined
Aug 12, 2021
Messages
78
Programming Experience
10+
Hello, C# Ladies and Guys,
I'm needing a generic ReadKey() method (in C#) that is able to read chars as keys like arrows or Ctrl. I know the Console.ReadKey() method but it is from the Console app type, I need one method that is independent on the project type. Yes, I already searched the web for "low level read key C#", and found some code examples, but with a few errors, or another with WPF target, and well, then I thought that it might be a good option to come here to ask for help to the experts. This is not a "gimme the codez" request, where the mystery is a logical algorithm and I don't want to get tired by using my brain, but a technical question about code I have no idea nor I used ever. Actually, it would be quite enough if you could give me any guidance on how/where I can find this code which should works generically independently of the project type.
The return type would be like ConsoleKeyInfo, which has a KeyChar and a Key members (if I remember correctly), that holds the char and the raw key respectively.
I will appreciate your help very much,
Thank you!
Regards
Pablo
 
Unfortunately, there is no generic solution that will work on all platforms that supports .NET (Core).

If you are only thinking of targeting Windows, then use the Win32 APIs by using P/Invoke. You can either really go very low level with GetKeyState() . Anything higher level than that where you want to key characters rather seeing what buttons are currently pressed, you'll need to actually act like a real Windows program and listen for WM_CHAR messages.

Based on your other thread regarding creating an empty project and then using SFML.NET, as I recall, SFML has its own keyboard input routines. It's been years since I last played with it, so my memory maybe fuzzy. As I recall though, SFML on Windows takes care of acting like a real Windows app so that it listen to the various Windows messages just like any other well behaved Windows app does.

For Mac and Linux, you'll need to find other low-level APIs for those platforms to get the keyboard inputs. On the other hand, if SFML is supposed to act like a generic framework that abstracts the OS for you, and it does have keyboard input routines, then you would just lean on SFML to read the keyboard for you.
 
Back
Top Bottom