I have a fairly simple question. How would I programmatically add/remove the workspaces found in mission control. I have seen this post here about changing to another space programmatically, and I think that it could be something similar to the answer, using CGSPrivate.h
. I don't need to worry about private frameworks, as it's not going on the app store.
EDIT: I also saw a post about modifying the com.apple.spaces.plist
and adding workspaces, but I have no Idea how I would add that, as the dict has UUID and other things.
Closest I could find to a solution for you was to achieve this via apple script - see ѺȐeallү's answer at the following link:
How can I programmatically add a space to mission control?
While in Mission Control this is the Accessibility Hierarchy of Dock (on my Mac, OS X 10.10):
The location of the workspace buttons is the middle of the remove button.
My test app:
Similar to
Willeke
I was able to accomplish this after many hour of code. Here is my code, then I'll explain what it does for any future people who come across this.In .h
My code is in AppDelegate (it is a menubar app).
In .m
Now lets go through the code step by step
For removing workspaces, the first method
removeAllWorkspaces
, is the very starting point.This code gets the number of workspaces open from the
com.apple.spaces.plist
file and then sets the variableworkspacesToRemove
. This variable is important for looping as it is hard to do afor-loop
when there are method chains (as I call them).Next, I call a method to open mission control by doing
CGEvents
. Then I move the mouse to the top corner of the screen to make sure the workspace icons are centered properly.Next, the code determines the position of the close button of the rightmost workspace using the
rectForWorkspaces
method.This is a pretty simple method, but it is the main part of what happens.
It calculated the rectangle of where the workspaces are going to be in mission control. Here is an image representing what it calculates:
I then take this rect, subtract 145 (workspace icon width), and click in the close button when it pops up.
This part loops until all workspaces (except 1) are closed.
FWI: The reason it is split into many methods is so I can loop back to a specific one and execute the methods after delays without blocking threads.
Yay complicated closing over!
The adding of workspaces is a lot easier.
It is only one method (
openWorkspaces:(NSInteger)numberToOpen
), and it opens mission control, moves mouse to position, and clicks number of times until all the workspaces have been added. Very simple.