How do I create a Cocoa window programmatically?

Steve McLeod picture Steve McLeod · Nov 24, 2008 · Viewed 54.7k times · Source

My Cocoa app needs some small dynamically generated windows. How can I programmatically create Cocoa windows at runtime?

This is my non-working attempt so far. I see no result whatsoever.

NSRect frame = NSMakeRect(0, 0, 200, 200);
NSUInteger styleMask =    NSBorderlessWindowMask;
NSRect rect = [NSWindow contentRectForFrameRect:frame styleMask:styleMask];

NSWindow * window =  [[NSWindow alloc] initWithContentRect:rect styleMask:styleMask backing: NSBackingStoreRetained    defer:false];
[window setBackgroundColor:[NSColor blueColor]];
[window display];

Answer

Jason Coco picture Jason Coco · Nov 24, 2008

The problem is that you don't want to call display, you want to call either makeKeyAndOrderFront or orderFront depending on whether or not you want the window to become the key window. You should also probably use NSBackingStoreBuffered.

This code will create your borderless, blue window at the bottom left of the screen:

NSRect frame = NSMakeRect(0, 0, 200, 200);
NSWindow* window  = [[[NSWindow alloc] initWithContentRect:frame
                    styleMask:NSBorderlessWindowMask
                    backing:NSBackingStoreBuffered
                    defer:NO] autorelease];
[window setBackgroundColor:[NSColor blueColor]];
[window makeKeyAndOrderFront:NSApp];

//Don't forget to assign window to a strong/retaining property!
//Under ARC, not doing so will cause it to disappear immediately;
//  without ARC, the window will be leaked.

You can make the sender for makeKeyAndOrderFront or orderFront whatever is appropriate for your situation.