Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

API to detect active session in Mac OS X with fast user switch

On Mac OS X Snow Leopard with fast user switching enabled, is there an API to detect whether or not my application is running in the active user session? I.e. the session currently attached to screen and keyboard.

Either Objective-C or C++ is fine.

like image 926
snowcrash09 Avatar asked Dec 15 '11 11:12

snowcrash09


3 Answers

I avoided using User Switch Notifications and instead have found two other possibilities:

  1. Use CGMainDisplayID() from Core Graphics. Store the main display ID when your app first starts and keep polling it. It will change to a different display ID when switching to another user. Problem with this is it may also change for other reasons e.g. changing which display is the primary display in a multi-screen setup.

  2. Use CGSessionCopyCurrentDictionary() also from Core Graphics, and retrieve the kCGSessionOnConsoleKey Boolean value from the dictionary. This indicates whether your user session is attached to console.

Both of these require polling but this is fine for my purposes. User Switch Notifications would be a better choice if you need to be event-driven.

like image 195
snowcrash09 Avatar answered Sep 27 '22 18:09

snowcrash09


From "Introduction to Multiple User Environments" i can only think of one thing that could fit your needs: User Switch Notifications. So if your application starts it clearly must be in the active session. Now you can use a user switch notification for setting the new state, i. e. that the application does not run anymore in the active session.

like image 33
Sebastian Dressler Avatar answered Sep 27 '22 17:09

Sebastian Dressler


This worked for me (10.14 / Swift 4)

        //Fast user switch out
    NSWorkspace.shared.notificationCenter.addObserver(
        self,
        selector: #selector(becameInactive),
        name: NSWorkspace.sessionDidResignActiveNotification,
        object: nil
    )

    //Fast user switch bak in
    NSWorkspace.shared.notificationCenter.addObserver(
        self,
        selector: #selector(becameActive),
        name: NSWorkspace.sessionDidBecomeActiveNotification,
        object: nil
    )

    // Switching workspace (spaces)
    NSWorkspace.shared.notificationCenter.addObserver(
        self,
        selector: #selector(workspaceSwitched),
        name: NSWorkspace.activeSpaceDidChangeNotification,
        object: nil
    )
like image 42
appsmatics Avatar answered Sep 27 '22 17:09

appsmatics