I'm working on a simple Mac app that detects when an external screen is unplugged, saves the location of all windows and once the external screen is plugged in again, restores all windows to its original position. (I know there are apps out there already, I'm just curious how this is done)
After a lot of searching, I finally managed to get all windows on screen by using
NSArray *openWindows = [[NSWorkspace sharedWorkspace] runningApplications];
CFArrayRef windowList = CGWindowListCopyWindowInfo(kCGWindowListOptionOnScreenOnly, kCGNullWindowID);
This would return something like
{
kCGWindowAlpha = 1;
kCGWindowBounds = {
Height = 22;
Width = 279;
X = 1559;
Y = 0;
};
kCGWindowIsOnscreen = 1;
kCGWindowLayer = 25;
kCGWindowMemoryUsage = 13596;
kCGWindowName = "";
kCGWindowNumber = 18;
kCGWindowOwnerName = SystemUIServer;
kCGWindowOwnerPID = 260;
kCGWindowSharingState = 1;
kCGWindowStoreType = 2;
},
{
kCGWindowAlpha = 0;
kCGWindowBounds = {
Height = 22;
Width = 1920;
X = 0;
Y = 0;
};
kCGWindowIsOnscreen = 1;
kCGWindowLayer = 25;
kCGWindowMemoryUsage = 5404;
kCGWindowNumber = 19;
kCGWindowOwnerName = SystemUIServer;
kCGWindowOwnerPID = 260;
kCGWindowSharingState = 1;
kCGWindowStoreType = 2;
},
I would then loop through the array and look at each individual window
for (int i = 0; i < CFArrayGetCount(windowList); i++) {
CFDictionaryRef ref = CFArrayGetValueAtIndex(windowList, i);
NSLog(@"%@", CFDictionaryGetValue(ref, kCGWindowBounds));
}
But this is where I got stuck, how can I first of all know on which screen a window is when working with multiple screens. And secondly, how can I adjust the window bounds later on? Does each application has its own ID? Or is there another method I could use?