Keyboard Input and character encoding
I'm trying to implement a editable text box type of thing, and I'm having a little trouble with keyboard input. The best choice for something like this would be handling keyboard events and adding characters that way, but from what I've seen there is currently no way to handle those events in an XNA project. Or is there?
So if I can't use events, is there any way to determine what character was pressed? Or am I just going to have to make a case for each key (and key combination)?
see my article on the falling characters game i wrote:
http://www.ziggyware.com/readarticle.php?article_id=49
Here is the meat of how to do keyboard key pressed events: (See the sample for a full explanation as well as a demo project)
if (pressedKeys != null)
{
foreach (Keys k in newKeys)
{
bool bFound = false;
foreach (Keys k2 in pressedKeys)
{
if (k == k2)
{
bFound = true;
break;
}
}
if (!bFound)
{
OnKeyPressed(k); //handle this key press
}
}
}
And here is how you get the key's character:
Fortunately in .NET you can use the Enum object to get the name of any enumeration! :)
Keys k = Keys.K;
string strPressedCharacter = Enum.GetName(typeof(Keys),k);
Thanks,
Ziggy
www.ziggyware.com
I'd actually already coded something that works exactly like what you've got there. The problem here is that Enum.GetName gives us a descriptive string rather than what the char actually is. For example the minus key gives back OEMMinus or something like that. I could of course set up a switch to convert every possibility (which is what i'm actually doing until a better solution comes along).
The other big problem with all this is that we're just looking at keys pressed... not characters sent. So we won't be able to tell the difference between a '!' and a '1', unless of course we poll for the shift key (which again, is what my current solution is).
It just seems silly that there's no way to do event driven input for things like this, when it's exactly what we need... not to mention built in to C#... I mean there's got to be Windows.Form stuff burried in there somewhere, right?
A robust solution would definately be better than the Enum solution :)
I've written many event driven key routines like the one you describe, however the sample i have there is just a basic implementation :)
I'd also be interested to hear any potential solutions to this conundrum - it feels wrong doing it this way.
Currently I'm doing the same as bocksnick I think - I set up a big list of valid input keys and test each one against my keys pressed this frame. I then cast the input key to a char and add it to a string. The method does not recognise shift, and numbers come out as D1, D2 etc.