6

I want to get the current workspace in my app. I found a way to achieve my goal from valexa's answer:

-(int)spaceNumber
{
    CFArrayRef windowsInSpace = CGWindowListCopyWindowInfo(kCGWindowListOptionAll | kCGWindowListOptionOnScreenOnly, kCGNullWindowID);      
    for (NSMutableDictionary *thisWindow in (NSArray *)windowsInSpace)    {
        if ([thisWindow objectForKey:(id)kCGWindowWorkspace]){
            return [[thisWindow objectForKey:(id)kCGWindowWorkspace] intValue];
        }
    }
    return -1;
}

But now(macOS 10.13.3 for my case) the kCGWindowWorkspace is not existed any more. So are there any other ways to achieve my goal?

Thanks in advance!

rmaddy
  • 314,917
  • 42
  • 532
  • 579
Zieng
  • 453
  • 1
  • 7
  • 17

1 Answers1

0

The GitHub utility WhichSpace [github.com/gechr/WhichSpace] will put a numeric icon in the toolbar, indicating which Desktop number is the current Space. This can be queried with Applescript:

tell application "System Events" ¬
  to tell process "WhichSpace" ¬
    to set temp to (title of menu bar items of menu bar 1)
return item 1 of temp

The following Swift code will call a function when the Desktop changes. That's also potentially useful.

NSWorkspace.shared.notificationCenter.addObserver(forName: 
  NSWorkspace.activeSpaceDidChangeNotification, object: nil, queue: nil,
    using: <the function you want to handle this event> )
August
  • 343
  • 3
  • 10