One Quickie

Grabbing the bits from the screen (Graphics->General)
(Many thanks to Paul Sobolik for giving us this an updated and more reliable version)
- (NSImage *) captureScreenImageWithFrame: (NSRect) frame
    // Fetch a graphics port of the screen

    CGrafPtr screenPort = CreateNewPort ();
    Rect screenRect;
    GetPortBounds (screenPort, &screenRect);

    // Make a temporary window as a receptacle

    NSWindow *grabWindow = [[NSWindow alloc] initWithContentRect: frame
                                              styleMask: NSBorderlessWindowMask
                                              backing: NSBackingStoreRetained
                                              defer: NO
                                              screen: nil];
    CGrafPtr windowPort = GetWindowPort ([grabWindow windowRef]);
    Rect windowRect;
    GetPortBounds (windowPort, &windowRect);
    SetPort (windowPort);

    // Copy the screen to the temporary window

    CopyBits (GetPortBitMapForCopyBits(screenPort),

    // Get the contents of the temporary window into an NSImage

    NSView *grabContentView = [grabWindow contentView];

    [grabContentView lockFocus];
    NSBitmapImageRep *screenRep;
    screenRep = [[NSBitmapImageRep alloc] initWithFocusedViewRect: frame];
    [grabContentView unlockFocus];

    NSImage *screenImage = [[NSImage alloc] initWithSize: frame.size];
    [screenImage addRepresentation: screenRep];

    // Clean up
    [grabWindow close];

    return (screenImage);

} // captureScreenImageWithFrame

borkware home | products | miniblog | rants | quickies | cocoaheads
Advanced Mac OS X Programming book