给定窗口ID,确定窗口所在的屏幕

时间:2011-10-21 14:15:03

标签: cocoa nswindow

假设我有窗口ID,有没有办法让NSScreen获取另一个进程的窗口?

我与以下代码非常接近,但信息字典没有说明窗口所在的屏幕。

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);

来自:CGWindowListCopyWindowInfo, kCGWindowLayer and window level

这里输出:

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;

我可以尝试从窗口边界计算屏幕,但我想知道是否有更好的方法。

1 个答案:

答案 0 :(得分:3)

此信息不可用的原因可能是因为窗口可以同时位于多个屏幕上。如果用户拖动窗口以使其中的一部分位于一个窗口中而其余部分位于另一个窗口中,则不存在当前屏幕。

您的窗口边界估计方法可能是最佳选择。