Reputation: 1300
I've tried looking for an answer here in previous posts, but I didn't find one.
I'm doing a MonoGame game, and I decided I want to have a event based keyboard handler.
So the KeyboardHandler class is a singleton class,
And right now it has:
- delegate void KeyPressEventHandler()
- events of that delegate for the four arrow keys
- static instance of the class for singleton
- get method for that instance
- A while(true) thread method and a method that creates a thread that calls that method.
The thread method is just a while(true) that checks if a keypress of any of the the four arrow keys have been pressed and activates their respective event if needed.
I want to be able to create a dictionary of <Keys, (event or whatever)>
so that I can for example:
void doSomething() { }
KeyboardHandler.Get().SubscribeToEvent(Keys.A, doSomething)
void SubscribeToEvent(Keys key, Action toSubscribe)
{
this.KeypressHandler[key] += new KeypressEventHandler(tobSubscribe)
}
And a method that would handle firing these event handlers of course.
But How do I declare such a dictionary?
EDIT: eventually implemented here: https://github.com/gioragutt/training/blob/master/MonoGameFirst/MonoGameFirst/BaseGameClasses/KeyboardHandler.cs
Upvotes: 2
Views: 949
Reputation: 6486
Just declare you dictionary as a Dictionary<Keys, Action>
. Then you just have to check whether your dictionary actually contains that key. Remember that the standard Action is just a method that has 0 input arguments and does not return a value. If you need, you could use one of the other Actions that accept a set number of input arguments. Your code might resemble something like this:
Setup your dictionary:
var keyHandlers = new Dictionary<Keys, Action>();
keyHandlers.Add(Keys.Back, () => Console.WriteLine("Handler for backspace"));
keyHandlers.Add(Keys.Enter, () => {
//some other statements,
//maybe set some class-level property
Console.WriteLine("Handler for enter ");
});
keyHandlers.Add(3, NameOfMethodThatMatchesActionDelegateSignature);
Then in the main event handler, check the dictionary and try to do stuff:
Action actionToDo;
bool actionRegistered = keyHandlers.TryGetValue(key, out actionToDo);
if (actionRegistered)
{
actionToDo.Invoke();
}
A demo that uses ints to register the actions instead of the Keys
enum.
Upvotes: 1