Solution for “My Mac OS X GUI program doesn’t get focus if it’s outside an application bundle”

This problem regularly comes up at the wxWidgets mailing list: You write an application for Mac OS X which utilizes a GUI and when you start the program, you can see the user interface, but the window doesn’t have the focus and also you can’t click it. So the window is not reactive in any way. Usually the answer is, that you should put your program in an application bundle, which is basically a folder which is called “something.app” (the executable needs to be copied to “Contents/MacOS” and you also might need to add an Info.plist file) and run the application bundle with “open something.app”. But there are situations where this is not really possible, e.g. you have some command line tool (PLplot program) and then you run some code which opens a GUI (wxWidgets driver for PLplot). If you write some easy program to calculate something and show a plot with the help of PLplot you don’t want to create an application bundle for that.

But there is a hack which I once found somewhere in the internet (I can’t find the source anymore, in this blog post this topic is shortly discussed without providing the whole solution and the text reminds me of what I read about that years ago, but it’s not the source I used) which uses some undocumented features of Mac OS X and may not work for future versions of Mac OS X. But from at least 10.4 on to 10.6.2 this hack still works, so you may be on the safe side for now. Anyway, you need to add

#ifdef __WXMAC__
    #include <Carbon/Carbon.h>
    extern "C" { void CPSEnableForegroundOperation(ProcessSerialNumber* psn); }
#endif

somewhere at the top of your code and then add

    /* this hack enables to have a GUI on Mac OSX even if the
     * program was called from the command line (and isn't a bundle) */
#ifdef __WXMAC__
     ProcessSerialNumber psn;

     GetCurrentProcess( &psn );
     CPSEnableForegroundOperation( &psn );
     SetFrontProcess( &psn );
#endif

e.g. somewhere at your program entrance . This will give focus to your wxWidgets app, although it’s not an application bundle. I use this hack successfully for the wxWidgets driver of PLplot for some years now, without problems. But as said there is no guarantee that this hack will work in future Mac OS X versions.

1 thought on “Solution for “My Mac OS X GUI program doesn’t get focus if it’s outside an application bundle”

  1. Thanks, thanks very much for this post! It just saved my day. I made a bundle and that fixed the misbehavior I was seeing :-/
    I’ll remember the hack you’ve shown for the future 🙂
    Thank you again

Leave a Reply

Your email address will not be published. Required fields are marked *

 

This site uses Akismet to reduce spam. Learn how your comment data is processed.