How to get the current workspace programmatically on macOS

2.3k views Asked by At

I would like to be able to tell at any time which mission control workspace the user is currently using programmatically on macOS 10.13. I could not find any working answer during my search. Any langage will do, and any workspace identifier works for me (uuid, workspace number...)

Thank you for the help!

3

There are 3 answers

0
Dad On

Looks like this requires undocumented API calls.

https://github.com/asmagill/hs._asm.undocumented.spaces/blob/master/CGSSpace.h

and

CG_EXTERN CGSSpaceID CGSGetActiveSpace(CGSConnectionID cid);

may do what you want, but this code hasn't been touched in 3 years so system/api may have migrated, and all the problems with using undocumented APIs apply.

Found this in the project https://github.com/asmagill/hs._asm.undocumented.spaces

haven't used or verified it.

2
simsula On
  • Download the private CGSInternal headers
  • Put them in a folder on your system
  • Go to your Projects Build Settings and add that folder to User Header Search Paths

Then you can do this:


#import "AppDelegate.h"
#import "CGSInternal/CGSSpace.h"

@implementation AppDelegate

typedef int CGSConnection;
extern CGSConnection _CGSDefaultConnection(void);

- (void)applicationDidFinishLaunching:(NSNotification *)aNotification {

    CGSSpaceID activeSpace = CGSGetActiveSpace(_CGSDefaultConnection());
    NSLog(@"activeSpace: %zu", activeSpace);

    CFArrayRef spaceArray = CGSCopySpaces(_CGSDefaultConnection(), kCGSAllSpacesMask);
    NSLog(@"allSpaces: %@", spaceArray);
}

@end
3
clemsam lang On

If you want a "working answer" use an indirect GUI "variable" to tell you where you are:

tell application "System Events" to text items 27 thru -1 of item 1 of (picture of every desktop as list) as string (<= shorter but politically in-correct)

set delimOrgs to text item delimiters
set text item delimiters to {"/"}
tell application "System Events" to set BGpict to ¬
     last text item of (picture of current desktop as text)
set text item delimiters to delimOrgs
return BGpict                         [improved: user3439894's suggestion]

… which e.g. returns "Lion.jpg" on one of my 4 workspaces, "Sierra.jpg" on another, which means I was using desktop 3 first and desktop 1 right now.