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.
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
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());