Detecting frontmost application changes…

How to detect frontmost application changes ?
You have to use Carbon code and install a handler for the kEventAppFrontSwitched event:
EventTypeSpec eventType;

eventType.eventClass = kEventClassApplication;
eventType.eventKind = kEventAppFrontSwitched;
EventHandlerUPP handlerUPP = NewEventHandlerUPP(appSwitched);
InstallApplicationEventHandler (handlerUPP, 1, &eventType, self, NULL);
And the handler code:
pascal OSStatus appSwitched (EventHandlerCallRef nextHandler, EventRef theEvent, void* userData) {
ProcessSerialNumber newSerial;

// your stuff goes here

return(CallNextEventHandler(nextHandler, theEvent));