Search code examples
objective-cxcodecocoanswindowmultiple-monitors

Display window on all screens


I'm trying to display window copies on all screens. See my code below. It only shows the borderless window correctly on the main screen. I don't see the other window anywhere.

The window is supposed to show 200px from the left and 200px from the top side.

I set origin.x to the screen height - 300 (= 200px spacing + 100px height of the window itself).

Any idea what I'm doing wrong?

- (void)displayOnAllScreens
{        
    NSArray *screenArray = [NSScreen screens];

    _tempWindows = [[NSMutableArray alloc] init];

    if ([screenArray count] == 1) {
        [self displayOnScreen:[NSScreen mainScreen]];
    } else {
        for (int i=0; i<[screenArray count]; i++) {
            [self displayOnScreen:[screenArray objectAtIndex:i]];
        }
    }
}

- (void)displayOnScreen:(NSScreen *)screen
{
    BOOL isMainScreen = NO;

    if (screen == [NSScreen mainScreen]) {
        isMainScreen = YES;
    }

    NSRect screenRect = [screen frame];

    NSRect frame = NSMakeRect(screenRect.origin.x + 200, screenRect.size.height - 300, 100, 100);

    NSWindow *_tempWindow;

    _tempWindow  = [[NSWindow alloc] initWithContentRect:frame
                                                     styleMask:NSBorderlessWindowMask
                                                       backing:NSBackingStoreBuffered
                                                         defer:NO];

    if (isMainScreen) {
        [_tempWindow setBackgroundColor:[NSColor lightGrayColor]];
    } else {
        [_tempWindow setBackgroundColor:[NSColor redColor]];
    }
       [_tempWindow makeKeyAndOrderFront:NSApp];
    [_tempWindow setAlphaValue:0.93];

    [_tempWindow setCollectionBehavior:NSWindowCollectionBehaviorCanJoinAllSpaces];

    [_tempWindows addObject:_tempWindow];
 }

Solution

  • NSWindow has a special initializer to specify which screen you want it on (you were actually just one parameter off!):

    initWithContentRect:styleMask:backing:defer:screen:
    

    The other form of the initializer assumes the main screen, which is why they were piling up like that.