0
votes

Default XNA input doesn't provide an event handler that may call some method during frame processing (between update calls, immediately when a key is pressed).

I tried using Nuclex.Input, but it has some flaws — keys like F10, Alt and Pause do not fire up assigned events. Some of those keys appear in GetKeyboard().GetState().GetPressedKeys() list, but some of them don't, which is unacceptable for making shortcuts.

I would be happy if there was a way to make the XNA's default input manager to work with events, but I haven't seen anyone say it's possible. So I'm probably looking for some other input manager that can give me any key press there can be with press/release event handler.

Or maybe there is some way to avoid using third-party library by using windows hooks like firing up handler event for any key press/release?

Or this whole XNA input way is whacked up and higher class game engines use a totally different approach?


I see everybody's been using XInput for the last few years.

2

2 Answers

0
votes

Here is some code from an old project of mine. It finds the difference between two KeyboardState objects. Specifically, it returns a KeyboardState containing the keys that are down in the second one but not the first one.

KeyboardState GetKeysPressedBetween(KeyboardState first, KeyboardState second)
{
    KeyboardState pressed = new KeyboardState();
    for (int i = 0; i < 8; i++)
    {
        FieldInfo currentStateI = typeof(KeyboardState).GetField("currentState" + i, BindingFlags.NonPublic | BindingFlags.Instance);
        uint firstCurrentStateI = (uint)currentStateI.GetValue(first);
        uint secondCurrentStateI = (uint)currentStateI.GetValue(second);
        currentStateI.SetValueDirect(__makeref(pressed), ~firstCurrentStateI & secondCurrentStateI);
    }
    return pressed;
}

This would normally be called once per frame, comparing the current state to the previous one.

The code could be modified to get the keys that were released, by replacing

~firstCurrentStateI & secondCurrentStateI

with

firstCurrentStateI & ~secondCurrentStateI
0
votes

For now I have resorted to using Nuclex.Input for my XNA game, but I'm still looking for better alternatives.

Some problems with Nuclex.Input are that it doesn't differentiate between left and right Shift or Ctrl buttons and doesn't detect some keys (including F10, left Alt, PrintScreen and Pause).