views:

559

answers:

4

Mac OS X Leopard has a virtual desktop implementation called Spaces. I want to programatically detect which space the user is currently on.

Cocoa is preferable but AppleScript is acceptable if there's no other way.

I've seen a couple of AppleScript implementations, but the techniques they used seemed a bit too hacky to use in production code (one relied on causing and error and then parsing the error message to get the current space, the other interrogated the Spaces menu GUI)

+11  A: 

Use HIWindowGetCGWindowID to get the CGWindowID for your WindowRef.

Use that ID with CGWindowListCreateDescriptionFromArray from CGWindow.h to get information on your window.

Look at the returned dictionary and extract the (optional) kCGWindowWorkspace key. That is your space ID for your window.

Andrew Grant
A: 

I know it's been some time since the question was asked, but I'm curious where you found those AppleScript solutions; I'm not able to find them (not an easy topic to search for).

Matt Todd
A: 

I know it's been some time since the question was asked, but I'm curious where you found those AppleScript solutions; I'm not able to find them (not an easy topic to search for).

He's not refering to applescript functions, those are functions in the Carbon Window manager ( a painfully complicated mess to navigate )

http://developer.apple.com/legacy/mac/library/documentation/Carbon/Reference/Window%5FManager/Reference/reference.html

+1  A: 

If anyone still cares, I've put together a little commandline util based on the answers here which you can get at http://github.com/shabble/osx-space-id

Shabble
+1000 if I could. Your a star Shabble for the git upload!
zaf