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);
DisposeEventHandlerUPP(appSwitched);
And the handler code:
pascal OSStatus appSwitched (EventHandlerCallRef nextHandler, EventRef theEvent, void* userData) {
ProcessSerialNumber newSerial;
GetFrontProcess(&newSerial);

// your stuff goes here

return(CallNextEventHandler(nextHandler, theEvent));
}