Skip to content

Instantly share code, notes, and snippets.

@jim-ec
Last active June 21, 2023 10:38
Show Gist options
  • Save jim-ec/2e50ce7b04e6d9db70f0eaf6a0a630e4 to your computer and use it in GitHub Desktop.
Save jim-ec/2e50ce7b04e6d9db70f0eaf6a0a630e4 to your computer and use it in GitHub Desktop.
Minimal Cocoa Example

Minimal Cocoa Sample

main.m

#import <Cocoa/Cocoa.h>

int main ()
{
    [NSAutoreleasePool new];
    [NSApplication sharedApplication];
    [NSApp setActivationPolicy:NSApplicationActivationPolicyRegular];
    id menubar = [[NSMenu new] autorelease];
    id appMenuItem = [[NSMenuItem new] autorelease];
    [menubar addItem:appMenuItem];
    [NSApp setMainMenu:menubar];
    id appMenu = [[NSMenu new] autorelease];
    id appName = [[NSProcessInfo processInfo] processName];
    id quitTitle = [@"Quit " stringByAppendingString:appName];
    id quitMenuItem = [[[NSMenuItem alloc] initWithTitle:quitTitle
        action:@selector(terminate:) keyEquivalent:@"q"] autorelease];
    [appMenu addItem:quitMenuItem];
    [appMenuItem setSubmenu:appMenu];
    NSWindowStyleMask styleMask = NSWindowStyleMaskTitled
        | NSWindowStyleMaskClosable
        | NSWindowStyleMaskMiniaturizable
        | NSWindowStyleMaskResizable
        | NSWindowStyleMaskFullSizeContentView;
    id window = [[[NSWindow alloc] initWithContentRect:NSMakeRect(0, 0, 200, 200)
            styleMask:styleMask
            backing:NSBackingStoreBuffered defer:NO]
            autorelease];
    [window cascadeTopLeftFromPoint:NSMakePoint(20, 20)];
    [window setTitle:appName];
    [window makeKeyAndOrderFront:nil];
    [NSApp activateIgnoringOtherApps:YES];
    [NSApp run];
    return 0;
}

Build command: clang main.m -framework Cocoa -o main

Links:

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment