Keylistener - How to example / Help needed

Yes here I go again, stuck! Damn I wish I had more understanding of C++ so I could just figure it all out by myself using the docs of which I wished each and everyone had a simple example on the top the “Class Reference” page.

My first JUCE project a game is coming along fine, I have added sound effects, and now need simple keyboard input to allow 1-2 players to control a graphics shape.

I started an Audio Application from Projucer. I have the main.cpp mostly left as is, and keeping everything in the MainComponent cpp and header files.

I header I got;

class MainComponent	:	public AudioAppComponent, 
						public HighResolutionTimer,
						public ChangeListener,
						public MixerAudioSource,
						public KeyListener
{
public:

	//==============================================================================
	MainComponent();
	~MainComponent();

	//==============================================================================
	bool keyPressed(const KeyPress& k, Component* c) override;
	...

and in cpp I got;

MainComponent::MainComponent()
{
    ...
	addKeyListener(this);
	setWantsKeyboardFocus(true);
	grabKeyboardFocus();
}

and further down I got;

bool MainComponent::keyPressed(const KeyPress& k, Component* c)
{
	if (k.getTextCharacter() == 'x') {
		// Update variable determining players horizontal position on screen
		x -= 1;
	}
	return false;
}

My project compiles fine, but it seems keyPressed is never reached. Perhaps addKeyListener(this) needs to go in main.cpp but I can’t figure out how exactly to do that.

First of all, every component is a keyListener anyway, so if you override keyPressed (const KeyPress & key) and keyUp in your Component, you can save the hassle of adding a key listener.

Apart from that setWantsKeyboardFocus (true) and grabKeyboardFocus() is good and necessary. However, grabKeyboardFocus() can only work once the constructor has finished and the app is on the screen. You can verify that by clicking on the app, that should give it focus, and afterwards it should react to your keypresses.

Later you can add the grabKeyboardFocus using:

Timer::callAfterDelay (100, [&] { grabKeyboardFocus(); });

Hope that helps

1 Like

Thank you very much! At least this time I was more on the right track :slight_smile: