1
0
Fork 0
mirror of https://github.com/Ellpeck/MLEM.git synced 2024-06-27 23:09:10 +02:00
MLEM/MLEM/Extensions/WindowExtensions.cs
2019-09-01 19:33:33 +02:00

49 lines
1.7 KiB
C#

using System;
using System.Reflection;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Input;
namespace MLEM.Extensions {
public static class WindowExtensions {
private static readonly EventInfo TextInput = typeof(GameWindow).GetEvent("TextInput");
public static bool AddTextInputListener(this GameWindow window, TextInputCallback callback) {
return new TextInputReflector(callback).AddToWindow(window);
}
public static bool SupportsTextInput() {
return TextInput != null;
}
public delegate void TextInputCallback(object sender, Keys key, char character);
private class TextInputReflector {
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);
}
}
}
}