Keyboard focus on application startup

(This is a continuation of tangent from: )

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

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…

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

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.

The suggestion on this page solved my problem easily: