Keyboard Input

SadConsole provides ways to process keyboard input, one such way is directly on a console or on a global scope. I’ll cover both here.
One thing that is important to note, the keys that are pressed and passed to SadConsole, are handled by the Host package, eg. MonoGame / SFML / others..

Keyboard input on focused consoles

I’ll setup a quick console, and override the ProcessKeyboard method to access the keyboard input.

public class CustomConsole : Console
{
	public CustomConsole(int width, int height) 
		: base(width, height)
	{ }

	public override bool ProcessKeyboard(Keyboard keyboard)
	{
		if (keyboard.KeysPressed.Count > 0)
		{
			System.Console.WriteLine("Pressed keys: " + string.Join(",", keyboard.KeysPressed.Select(a => a.Character)));
		}
		return base.ProcessKeyboard(keyboard);
	}
}

Now setting it as starting console, we can test it out.

.SetStartingScreen(a => new CustomConsole(90, 30))

Note: If the console loses focus, it won’t pickup the key presses anymore.
This can happen when you click on another console, then focus shifts to the new console.
You can manually change focus on the console by setting it directly:

console.IsFocused = true;

Global keyboard input

Keyboard input can also be checked on a global scale, for example if you need your ESC key to always open the main menu in your game, no matter where on which console you currently are focused.

The keyboard can be access through:

Game.Instance.Keyboard

It is usually done in the FrameUpdate event which runs every frame.

static void OnFrameUpdate(object sender, GameHost host)
{
	if (Game.Instance.Keyboard.IsKeyPressed(Keys.Escape))
	{
		System.Console.WriteLine("Escape key pressed!");
	}
}

Add it to the game configuration:

new Game.Configuration().UseFrameUpdateEvent(OnFrameUpdate)

Known issues with MonoGame

MonoGame has some known issues with keys on french keyboards (azerty)
https://github.com/MonoGame/MonoGame/issues/5715

So it could be that some keys don’t come through properly, or are mapped wrongly.
But this is based on the host package used.

Leave a comment

Design a site like this with WordPress.com
Get started