Have to click into component to make keyboard shortcuts work


#1

Hi,

I added keyboard shortcuts to my JUCE application via an ApplicationCommandManager - but they only work after clicking into the component once.

How can I make the components react to keyboard shortcuts without the need to first click into the component?

Thanks for your help,
Dietrich

PS: I tried to add setWantsKeyboardFocus(true) and grabKeyboardFocus() to the components in all kind of permutations, but it didn’t solve the problem.


#2

Two misunderstandings that people make about grabKeyboardFocus are:

  • Calling it before your component is actually on-screen. Unless the component and all its parents are visible and their window actually exists, then they can’t have focus.

  • Expecting it to work when the actual app doesn’t have focus. Certainly in some debuggers I find that when your app launches, it can’t get focus until the user clicks it. That’s an OS behaviour, not something you can change in the program.


#3

Hi Jules,

Thank you very much for your answer!

Calling it before your component is actually on-screen. Unless the component and all its parents are visible and their window actually exists, then they can’t have focus.

Where would I do that? Is there some hook which gets called when all parents are visible and where I could put my call to grabKeyboardFocus()?

I tried all kind of different positions to call grabKeyboardFocus() - in the constructor of the component, after calling addAndMakeVisible(), after calling resized(), …

Expecting it to work when the actual app doesn’t have focus. Certainly in some debuggers I find that when your app launches, it can’t get focus until the user clicks it. That’s an OS behaviour, not something you can change in the program.

That is what I thought as well. But the shortcut Cmd-Q added by

    menu.addCommandItem(commandManager, StandardApplicationCommandIDs::quit);

works. So the application seems to have focus. (Of course, it could be that this is actually a shortcut of Xcode to terminate the program :slight_smile:

Thanks again,

Dietrich


#4

This is a very useful bit of information that would make a nice addition to the doc for the grabKeyboardFocus() method.

Also, why not add an assertion inside it to warn people when its invocation will have no effect? Something like:

/* If you hit this, the Component is not showing on screen yet, thus it cannot get focus.
The net result is that this call to grabKeyboardFocus() will have no effect */
jassert (isShowing());

#5

That’s a really good idea! It does seem to be something that often confuses people.