Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
714 views
in Technique[技术] by (71.8m points)

cocoa - Determine which screen a window is on given the window ID

Is there a way to get the NSScreen for a window of another process assuming that I have the window id?

I got pretty close with the following code, but the info dictionary doesn't say which screen the window is on.

CFArrayRef windowArray = CGWindowListCopyWindowInfo(kCGWindowListOptionOnScreenOnly, kCGNullWindowID);
NSArray*  windowList = (NSArray*)CGWindowListCopyWindowInfo(kCGWindowListOptionOnScreenOnly, kCGNullWindowID);
NSUInteger count = [windowList count];
for (NSUInteger i = 0; i < count; i++)
{
    NSDictionary*   nswindowsdescription = [windowList objectAtIndex:i];
    NSNumber* windowid = (NSNumber*)[nswindowsdescription objectForKey:@"kCGWindowNumber"];
    if(windowid)
    {
        if ([windowid integerValue] == appWeAreLookingForWindowId)
        {
            Warning(@"Found it: %@", nswindowsdescription);
        }
    }
}
CFRelease(windowArray);

From: CGWindowListCopyWindowInfo, kCGWindowLayer and window level

Here the output:

kCGWindowAlpha = 1;
kCGWindowBounds =     {
    Height = 1010;
    Width = 1600;
    X = 284;
    Y = 43;
};
kCGWindowIsOnscreen = 1; // This is not the screen id, by the way
kCGWindowLayer = 0;
kCGWindowMemoryUsage = 7709736;
kCGWindowName = "osx - CGWindowListCopyWindowInfo, kCGWindowLayer and window level - Stack Overflow";
kCGWindowNumber = 4000;
kCGWindowOwnerName = Safari;
kCGWindowOwnerPID = 240;
kCGWindowSharingState = 1;
kCGWindowStoreType = 2;
kCGWindowWorkspace = 1;

I could try to calculate the screen from the window bounds, but I'm wondering if there's a better way.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The reason this information is not available is probably because a window can be on more than one screen at once. If the user has dragged the window so that a portion of it is in one window and the rest in another, there is no such thing as the current screen.

Your window bounds estimation method is probably the best option.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...