Detecting a keypress

I am stunned that I don't seem to be able to do such a simple thing.

 Firstly in juce_Component.h I find:

virtual bool keyPressed (const KeyPress& key);

However if I make my own override, it doesn't get hit.

There is another definition for keyPressed in juce_KeyListener.h

Reading up, it looks like I need something like this:

class MainContentComponent : public AudioAppComponent, private KeyListener

    bool keyPressed(const KeyPress &k, Component *c) override
        ...breakpoint never hits!...

I run my code, click inside my app window to make sure it has focus, and press a key.

Setting a breakpoint on the first line of keyPressed handler, it never hits!

Instead OSX gives me the 'keystroke got bounced' dink sound.

I've tried also supplying an override for the 1-param signature. But nothing gets hit.




im on mobile, can't remember if that's set by default or not.

Justin, thanks -- works a treat!

Here is a minimal code example:

class MainContentComponent : public AudioAppComponent, private KeyListener { 
    MainContentComponent() { 
        //grabKeyboardFocus(); <-- seems to have no effect
    bool keyPressed(const KeyPress &k, Component *c) override {
        if( k.getTextCharacter() == 'x' ) ...

I think it would really help newcomers to have this code in a comment at the top of juce_KeyListener.h -- that setWantsKeyboardFocus really killed me. It is hiding in juce_Component.h which is a massive file!

 It would be nice to know, for the sake of completeness, why juce_Component.h provides its own virtual keyPressed method.

ok, after testing, it turns out this is sufficient:

class MainContentComponent : public AudioAppComponent
    MainContentComponent() { setWantsKeyboardFocus(true); } 

    bool keyPressed(const KeyPress &k) override {
        if( k.getTextCharacter() == 'x' ) ...

i.e. a component automatically implements a KeyListener.

So maybe this information could be given in juce_KeyListener.h... or do I just suck particularly hard at mining information?  How would a smart person go about getting this knowledge?


the JuceDemo uses almost every class written in JUCE.   that's the best place to start to see how to use a class or feature IMO. 

I agree, its bitten me a few times myself, which is why it was still on the brain!  Maybe a gentle assert in the library here or there? (adding a  keypress listener without it being WantingKeypress?)

I just spent 30 minutes trying to figure this out, I am so glad I found this thread! I totally agree that the need to setWantsKeyboardFocus should be mentioned somewhere more visible.

Otherwise, a visible recommendation to all new developers to dig into the Demo project would be appreciated (since, according to the comments, it seems to be pretty relevant). I personally read all tutorials in the website, but afterwards started programming without going into the examples directory.