Keyboard focus on application startup


#1

(This is a continuation of tangent from: http://www.rawmaterialsoftware.com/viewtopic.php?f=4&t=7231 )

The issue is that on Mac OS X, when the application starts up, the content component does not have keyboard focus, and will not until the user clicks in the content component. The problem is that even if you call grabKeyboardFocus() in the application initialise, the content component still will not be focused.

I have a theory on why this happens and a workaround…

Theory: The content component can not be focused until it is visible and active. This can take an arbitrary amount of time during app start up and JUCE is passing a message internally to update the state of the app so that grabKeyboardFocus can take effect. In other words, until the windowing system gives the go-ahead, grabKeyboardFocus will do nothing. You have to wait for the message stack to flush before sending grabKeyboardFocus.

Workaround: Since you have to wait for the message stack to flush through on startup, all you have to do is post a message via the juce::MessageListener and the action taken on this message is to call grabKeyboardFocus, and post the same message again until hasKeyboardFocus returns true.

void handleMessage(const juce::Message& Message)
{
  //...identify contents of Message...
#ifdef JUCE_MAC
    if(!GUIContent->hasKeyboardFocus(false))
      postMessage(Message);
    GUIContent->grabKeyboardFocus();
#endif
}

This problem doesn’t seem to exist on Windows (not surprising since the internal window code is completely different). It would great though if JUCE could handle this automatically. Maybe Jules could weigh in…


#2

Hmm… Yes, your theory sounds right to me. Not immediately clear how I could work around it in a generic way though… Suggestions welcome!


#3

FWIW, I’ve been solving this the same general way for quite awhile. When I first encountered it, I did some digging, but didn’t see a clearer workaround.


#4

The suggestion on this page solved my problem easily:

http://www.juce.com/forum/topic/cant-set-keyboard-focus