import com.intellij.ui.mac.foundation.MacUtil; //导入方法依赖的package包/类
@Nullable
private static BufferedImage captureScreen(@Nullable Window belowWindow, @NotNull Rectangle rect) {
ID pool = Foundation.invoke("NSAutoreleasePool", "new");
try {
ID windowId = belowWindow != null ? MacUtil.findWindowFromJavaWindow(belowWindow) : null;
Foundation.NSRect nsRect = new Foundation.NSRect(rect.x, rect.y, rect.width, rect.height);
ID cgWindowId = windowId != null ? Foundation.invoke(windowId, "windowNumber") : ID.NIL;
int windowListOptions = cgWindowId != null
? FoundationLibrary.kCGWindowListOptionOnScreenBelowWindow
: FoundationLibrary.kCGWindowListOptionAll;
int windowImageOptions = FoundationLibrary.kCGWindowImageNominalResolution;
ID cgImageRef = Foundation.cgWindowListCreateImage(nsRect, windowListOptions, cgWindowId, windowImageOptions);
ID bitmapRep = Foundation.invoke(Foundation.invoke("NSBitmapImageRep", "alloc"), "initWithCGImage:", cgImageRef);
ID nsImage = Foundation.invoke(Foundation.invoke("NSImage", "alloc"), "init");
Foundation.invoke(nsImage, "addRepresentation:", bitmapRep);
ID data = Foundation.invoke(nsImage, "TIFFRepresentation");
ID bytes = Foundation.invoke(data, "bytes");
ID length = Foundation.invoke(data, "length");
ByteBuffer byteBuffer = Native.getDirectByteBuffer(bytes.longValue(), length.longValue());
Foundation.invoke(nsImage, "release");
byte[] b = new byte[byteBuffer.remaining()];
byteBuffer.get(b);
return ImageIO.read(new ByteArrayInputStream(b));
}
catch (Throwable t) {
LOG.error(t);
return null;
}
finally {
Foundation.invoke(pool, "release");
}
}