简体   繁体   中英

How to capture the screen and save it to the file in Xamarin.Mac

I'm not a experienced developer and i have a problem.

I don't understand how to make screenshot and save it to the file.

[DllImport("/System/Library/Frameworks/ApplicationServices.framework/Versions/A/Frameworks/CoreGraphics.framework/CoreGraphics")]
    private static extern IntPtr CGWindowListCreateImage(RectangleF screenBounds, CGWindowListOption windowOption, uint windowID, GWindowImageOption imageOption);
partial void ButtonClicked (Foundation.NSObject sender) {

            IntPtr screenShot = CGWindowListCreateImage ((RectangleF)NSScreen.MainScreen.Frame, CGWindowListOption.IncludingWindow,
                0, CGWindowImageOption.Default);

            CGImage img = new CGImage(screenShot);
            NSBitmapImageRep imgRep = new NSBitmapImageRep(img);

            NSImage imgf = new NSImage(img, NSScreen.MainScreen.Frame.Size);   
        }

Not sure it's working properly. Can anyone help?

This snippet would capture the current screen and save the result as a PNG to the desktop:


[DllImport("/System/Library/Frameworks/ApplicationServices.framework/Versions/A/Frameworks/CoreGraphics.framework/CoreGraphics")]
static extern IntPtr CGWindowListCreateImage(CGRect screenBounds, CGWindowListOption windowOption, uint windowID, CGWindowImageOption imageOption);

public override void ViewDidLoad()
{
    base.ViewDidLoad();

    using (var pool = new NSAutoreleasePool())
    {
        CGRect fullScreenBounds = NSScreen.MainScreen.Frame;
        IntPtr imageRef = CGWindowListCreateImage(fullScreenBounds, CGWindowListOption.All, 0, CGWindowImageOption.Default);
        var cgImage = new CGImage(imageRef);
        var filePath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Desktop), "StackOverflow.png");
        var fileURL = new NSUrl(filePath, false);
        var imageDestination = CGImageDestination.Create(fileURL, UTType.PNG, 1);
        imageDestination.AddImage(cgImage);
        imageDestination.Close();
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM