Capturing Displays

If you’re writing an immersive application such as a game or a presentation program, you may want to do full-screen drawing.

A common approach is to capture the display you want to use. When you capture a display, you have exclusive use of the display. Other applications and system services are not allowed to use the display or change its configuration. In addition, they are not notified of display changes, thus preventing them from repositioning their windows and the Finder from repositioning desktop icons.

To capture a single display, call the function CGDisplayCapture. To capture all online displays at once, call CGCaptureAllDisplays. By default, a captured screen is filled with black color; you have the option of disabling this feature if you capture using the functions CGDisplayCaptureWithOptions or CGCaptureAllDisplaysWithOptions.

After capturing a display, there are several drawing options:

When you are finished using a captured display, you should release it by calling CGDisplayRelease or CGReleaseAllDisplays.

Listing 1 shows how to capture the main display and draw a text string using Quartz 2D. A detailed explanation for each numbered line of code appears following the listing.

Listing 1  Capturing the main display

char *text = "Hello, World!";
CGDirectDisplayID display = kCGDirectMainDisplay; // 1
CGError err = CGDisplayCapture (display); // 2
if (err == kCGErrorSuccess)
{
    CGContextRef ctx = CGDisplayGetDrawingContext (display); // 3
    if (ctx != NULL)
    {
        CGContextSelectFont (ctx, "Times-Roman", 48, kCGEncodingMacRoman);
        CGContextSetTextDrawingMode (ctx, kCGTextFillStroke);
        CGContextSetRGBFillColor (ctx, 1, 1, 1, 0.75);
        CGContextSetRGBStrokeColor (ctx, 1, 1, 1, 0.75);
        CGContextShowTextAtPoint (ctx, 40, 40, text, strlen(text)); // 4
        sleep (4); // 5
    }
    CGDisplayRelease (display); // 6
}

Here’s what the code does:

  1. Gets the display ID of the main display.

  2. Captures the main display and changes the color to black. An error is returned only if the display has been captured by another application.

  3. Gets a Quartz graphics context associated with the captured display.

  4. Draws the text string in the lower-left corner of the screen.

  5. Suspends processing for a few seconds to allow the user to read the text.

  6. Releases the captured display.