Skip to main content
2 of 2
deleted 11 characters in body
David Gouveia
  • 25k
  • 5
  • 88
  • 127

There's a way if you don't mind using a bit of reflection, but I'm not sure I'd recommend it, especially since the title mentions efficiency. But I'll describe it anyway. I'll assume there's a subset of keys you want to cover, and not the entire Keys enumeration. If you want to cover every key, iterate directly over the enumeration values instead of using the array below:

  1. Add every key you're interested in to an array:

     public Keys[] keys = {Keys.A, Keys.B, Keys.C};
    
  2. Create the events for these keys. I'll use a simple Action delegate which has no parameters and no return value (add other types of events).

     public event Action APressed;
     public event Action BPressed;
     public event Action CPressed;
    
  3. Next we need an utility method to call an event by name. This is where the reflection comes in. Once again I'll assume that there are no parameters to the events, and I'll place the method in the same class that stores the events:

     private void RaiseEventByName(string eventName)
     {
         var eventDelegate = (MulticastDelegate)GetType().GetField(eventName, BindingFlags.Instance | BindingFlags.NonPublic).GetValue(this);
         if (eventDelegate != null)
             foreach (var handler in eventDelegate.GetInvocationList())
                 handler.Method.Invoke(handler.Target, null);
     }
    
  4. Finally our Update loop becomes something like (add logic for other states):

     foreach(Keys key in keys)
         if (currentKeyboardState.IsKeyDown(key) && previousKeyboardState.IsKeyUp(key))
             RaiseEventByName(key.ToString() + "Pressed");
    
David Gouveia
  • 25k
  • 5
  • 88
  • 127