how to get NSWindow size from kCGWindowNumber?

1.3k Views Asked by At
- (void) GetClientRect 

    NSArray *screenArray = [NSScreen screens];
    NSScreen *mainScreen = [NSScreen mainScreen];
    unsigned screenCount = [screenArray count];
    unsigned index  = 0;

    for (index; index < screenCount; index++)
    {
        NSScreen *screen = [screenArray objectAtIndex: index];
        NSRect screenRect = [screen visibleFrame];
        NSString *mString = ((mainScreen == screen) ? @"Main" : @"not-main");

        NSLog(@"Screen #%d (%@) Frame: %@", index, mString, NSStringFromRect(screenRect));
    }
}

Above method is use to get frame for mainscreen. But i want method which return Screen size of NSWindow whose kCGWindowNumber have been passed. Any idea ?!

1

There are 1 best solutions below

9
On

Why are you working with a CGWindowID (which is what I assume you meant by kCGWindowNumber)? That's a very unnatural thing to do in most circumstances.

Anyway, you can call CGWindowListCopyWindowInfo(0, theWindowID) and examine the dictionary in the first element of the returned array. Use the key kCGWindowBounds to get a dictionary representation of the bounds rectangle and then CGRectMakeWithDictionaryRepresentation() to convert that to a CGRect.


Are you looking for how to convert the NSWindow -frame, which is in Cocoa's coordinate system, to the Core Graphics coordinate system? The Cocoa coordinate system has its origin at the bottom-left of the primary display, with Y increasing in the up direction. The Core Graphics coordinate system has its origin at the top-left of the primary display, with Y increasing in the down direction.

So, the conversion looks like this:

NSWindow* window = /* ... comes from wherever ... */;
NSRect frame = window.frame;
frame.origin.y = NSMaxY([NSScreen.screens.firstObject frame]) - NSMaxY(frame);
CGRect cgbounds = NSRectToCGRect(frame);