1
0
Fork 0
mirror of https://github.com/Ellpeck/MLEM.git synced 2024-06-22 21:09:09 +02:00

made windowextensions a lot cleaner

This commit is contained in:
Ellpeck 2019-12-05 22:15:49 +01:00
parent 5d9c480160
commit af7fb342d7

View file

@ -6,41 +6,25 @@ using Microsoft.Xna.Framework.Input;
namespace MLEM.Extensions {
public static class WindowExtensions {
private static readonly EventInfo TextInput = typeof(GameWindow).GetEvent("TextInput");
private static readonly bool TextInputSupported = typeof(GameWindow).GetEvent("TextInput") != null;
public static bool AddTextInputListener(this GameWindow window, TextInputCallback callback) {
return new TextInputReflector(callback).AddToWindow(window);
if (!SupportsTextInput())
return false;
TextInputAdder.Add(window, callback);
return true;
}
public static bool SupportsTextInput() {
return TextInput != null;
return TextInputSupported;
}
public delegate void TextInputCallback(object sender, Keys key, char character);
private class TextInputReflector {
private static class TextInputAdder {
private readonly TextInputCallback callback;
public TextInputReflector(TextInputCallback callback) {
this.callback = callback;
}
public bool AddToWindow(GameWindow window) {
if (TextInput == null)
return false;
var handler = this.GetType().GetMethod(nameof(this.OnTextInput), new[] {typeof(object), typeof(EventArgs)});
if (handler == null)
return false;
TextInput.AddEventHandler(window, Delegate.CreateDelegate(TextInput.EventHandlerType, this, handler));
return true;
}
public void OnTextInput(object sender, EventArgs args) {
var type = args.GetType();
var key = (Keys) type.GetProperty("Key").GetValue(args);
var character = (char) type.GetProperty("Character").GetValue(args);
this.callback.Invoke(sender, key, character);
public static void Add(GameWindow window, TextInputCallback callback) {
window.TextInput += (sender, args) => callback(sender, args.Key, args.Character);
}
}