Getting notified when the current application changes in Cocoa

前端 未结 2 573
青春惊慌失措
青春惊慌失措 2020-12-23 18:33

I want to be notified when the current application will change. I looked at NSWorkspace. It will send notifications only when your own application becomes active or loses th

2条回答
  •  情歌与酒
    2020-12-23 18:46

    Thank you Jason. kEventAppFrontSwitched in Carbon Event Manager is the magic word

    - (void) setupAppFrontSwitchedHandler
    {
        EventTypeSpec spec = { kEventClassApplication,  kEventAppFrontSwitched };
        OSStatus err = InstallApplicationEventHandler(NewEventHandlerUPP(AppFrontSwitchedHandler), 1, &spec, (void*)self, NULL);
    
        if (err)
            NSLog(@"Could not install event handler");
    }
    
    - (void) appFrontSwitched {
        NSLog(@"%@", [[NSWorkspace sharedWorkspace] activeApplication]);
    }
    

    And the handler

    static OSStatus AppFrontSwitchedHandler(EventHandlerCallRef inHandlerCallRef, EventRef inEvent, void *inUserData)
    {
        [(id)inUserData appFrontSwitched];
        return 0;
    }
    

提交回复
热议问题