仅在应用程序窗口中以mac编程方式截取屏幕截图

Bit*_*ttu 9 macos cocoa screenshot objective-c

我必须添加截图到我的OSX应用程序的能力,但Apple演示只给我整个屏幕图像,我只想要我的应用程序窗口图像.

我的代码是:

NSInteger displaysIndex = 0;
if(displays != nil)
{
    free(displays);
}


CGError             err = CGDisplayNoErr;
CGDisplayCount      dspCount = 0;

/* How many active displays do we have? */
err = CGGetActiveDisplayList(0, NULL, &dspCount);

/* If we are getting an error here then their won't be much to display. */
if(err != CGDisplayNoErr)
{
    return;
}
/* Allocate enough memory to hold all the display IDs we have. */
displays = calloc((size_t)dspCount, sizeof(CGDirectDisplayID));

// Get the list of active displays
err = CGGetActiveDisplayList(dspCount,
                             displays,
                             &dspCount);

/* Make a snapshot image of the current display. */
CGImageRef image = CGDisplayCreateImage(displays[displaysIndex]);
Run Code Online (Sandbox Code Playgroud)

我应该在代码中更改什么,以便只获取应用程序的窗口?

Sol*_*oft 7

简单.

NSImage *captureImage  = [[NSImage alloc] initWithData:[self.view dataWithPDFInsideRect:[self.view bounds]]];
Run Code Online (Sandbox Code Playgroud)

请检查并让我知道.这是捕获的当前活动窗口.

  • 这将仅捕获视图及其后代的内容; 即使你将其解决到窗口的内容视图,它仍将排除窗口的框架.此外,您可以通过将焦点锁定在图像上并向视图发送一个`drawRect:`消息(通常没有其他保证,但在这种情况下适当)或使用`bitmapImageRepForCachingDisplayInRect:`来跳过与PDF的转换.该图像代表的相应方法,并将代码添加到空图像. (3认同)

Pet*_*sey 7

要真正把你的窗口的屏幕截图,包括它的框架和阴影,让你的窗口windowNumber,并传递给CGWindowListCreateImage函数.