Can I get the current active user information (for macOS)?

There's the NSWorkspaceSessionDidBecomeActiveNotification et al, but that doesn't say who the current user is. Is there a way to find out that? (I mean, I could have a LaunchAgent that send "I've become active!" log message or something, and then use the most recent one. Is there another way?)

Answered by Claude31 in 691137022
Accepted Answer

Oooh! CSIdentityQueryCreateForCurrentUser looks like it, maybe? I will experiment! Thank you! 😄

Edited to Add

Yes, that worked! My code here is really ugly, but it does seem to work. So thank you very much!

{

	CSIdentityQueryRef query;

	CFErrorRef error;

	CFArrayRef identityArray;

	

// create the identity query based on name

	query = CSIdentityQueryCreateForCurrentUser(kCFAllocatorDefault);

 

// execute the query

	if (CSIdentityQueryExecute(query, kCSIdentityQueryGenerateUpdateEvents, &error))

	{

		printf("Success!\n");

		// retrieve the results of the identity query

		identityArray = CSIdentityQueryCopyResults(query);

		printf("Got %lu entries in the array\n", CFArrayGetCount(identityArray));

		for (size_t indx = 0; indx < CFArrayGetCount(identityArray); indx++) {

			CSIdentityRef identity = (CSIdentityRef)CFArrayGetValueAtIndex(identityArray, indx);

			CFStringRef name = CSIdentityGetPosixName(identity);

			const size_t maxSize = 1024;

			char *buffer = (char *)malloc(maxSize);

			if (CFStringGetCString(name, buffer, maxSize,

					       kCFStringEncodingUTF8)) {

				printf("Current user = %s\n", buffer);

			} else {

				printf("Could not get user string?\n");

			}

		}

		// do something with identityArray

		//     return (CSIdentityRef)CFArrayGetValueAtIndex(users, 0);

		

 

 

	}

	CFRelease(query);

}

Oh darn it! No, that doesn't work! I forgot to test while actually using FUS, and in the one session, it continues to show the same user, even if I switch to between users. :(

Can I get the current active user information (for macOS)?
 
 
Q