Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Make Cocoa Window Fullscreen

I'm currently in the process of adding a fullscreen view to my OpenGL window in OS X. I'm not using OS X's "fullscreen mode" because I don't like the idea of taking over the users screen.

I have my own custom window class derived from NSWindow and in that class, I've overwritten the toggleFullscreen: selector:

- (void)toggleFullScreen:(id)sender
{
    _fullscreen = !_fullscreen;
    if(_fullscreen) {
        NSRect screenRect = [[NSScreen mainScreen] frame];
        [self setStyleMask:NSBorderlessWindowMask];
        [self setFrame:screenRect display:YES];
        [self setLevel:NSMainMenuWindowLevel+1];
        [self setOpaque:YES];
        [self setHidesOnDeactivate:YES];
    } else {
        NSRect screenRect = [[NSScreen mainScreen] frame];
        unsigned int width = (unsigned int)(screenRect.size.width/2.0f);
        unsigned int height = (unsigned int)(screenRect.size.height/2.0f);
        NSRect frame = NSMakeRect(0, screenRect.size.height-height, width, height);

        [self setStyleMask:NSTitledWindowMask | NSResizableWindowMask];
        [self setFrame:frame display:YES];
        [self setLevel:NSNormalWindowLevel];
        [self setOpaque:YES];
        [self setHidesOnDeactivate:NO];
    }
}

This seems to work mostly correctly, toggling between a fullscreen window (per Apple's documentation here) and a window at half the screens resolution.

The problem is that toggling between the two modes makes my window "lose focus". If I hit the keyboard shortcut I'm using right after I switch the mode, I get the OS X error "beep". I have to click in the window to "reactivate" it before I can use the toggle again.

I've tried adding a [self makeKeyAndOrderFront:nil]; to my function, but that doesn't fix the issue. All I need is a way to keep the window "focused" during the transition. Except for that issue, this method works perfectly and requires no changes to my NSView.

Edit

Not sure if its relevant, but I'm creating this window programmatically, not loading it from a Nib.

like image 970
Kyle Avatar asked Sep 01 '25 22:09

Kyle


1 Answers

An even easier method, which appears to be the correct modern way (as of Lion)...

In my NSApplicationDelegate's init method (sorry I'm new so my terms are wrong), after creating the window...

[window setCollectionBehavior:(NSWindowCollectionBehaviorFullScreenPrimary)];

Then fire off a toggleFullScreen, say from your menu, with target = nil.

It will then create a new named desktop with the icon, slide your window to it and make it fullscreen. Just like Google Chrome or Safari when you make them fullscreen. I too am doing it without a nib or xib or whatever the kids call it these days.

This page talks about doing it the Interface Builder way.

This is the official Apple docs on the subject.

like image 63
burito Avatar answered Sep 04 '25 11:09

burito