How can I copy a screenshot of my Bing Maps image to the Clipboard in Winforms?

In my winforms app, I want to allow the user to copy a screenshot of the Bing Maps component to the clipboard (at least).

I found the following code, from here, which goes above and beyond that, but it doesn't compile for me.

SaveScreenshot(this.userControl11.myMap, "MapScreenshot.png"); // code in menu item click handler

private async void SaveScreenshot(FrameworkElement captureSource, string suggestedName)
{
    //Create a FileSavePicker.
    var savePicker = new Windows.Storage.Pickers.FileSavePicker()
    {
        DefaultFileExtension = ".png",
        SuggestedFileName = suggestedName,
        SuggestedStartLocation = Windows.Storage.Pickers.PickerLocationId.PicturesLibrary
    };

    savePicker.FileTypeChoices.Add(".png", new System.Collections.Generic.List<string> { ".png" });

    //Prompt the user to select a file.
    var saveFile = await savePicker.PickSaveFileAsync();

    //Verify the user selected a file.
    if (saveFile != null)
    {                
        using (var fileStream = await saveFile.OpenAsync(Windows.Storage.FileAccessMode.ReadWrite))
        {
            //Capture the screenshot and save it to the file stream.
            await ScreenshotToStreamAsync(captureSource, fileStream);
        }
    }
}

private async Task ScreenshotToStreamAsync(FrameworkElement element, IRandomAccessStream stream)
{
    var renderTargetBitmap = new Windows.UI.Xaml.Media.Imaging.RenderTargetBitmap();
    await renderTargetBitmap.RenderAsync(element);

    var pixelBuffer = await renderTargetBitmap.GetPixelsAsync();

    var dpi = Windows.Graphics.Display.DisplayInformation.GetForCurrentView().LogicalDpi;

    var encoder = await BitmapEncoder.CreateAsync(BitmapEncoder.PngEncoderId, stream);
    encoder.SetPixelData(
        BitmapPixelFormat.Bgra8,
        BitmapAlphaMode.Ignore,
        (uint)renderTargetBitmap.PixelWidth,
        (uint)renderTargetBitmap.PixelHeight,
        dpi,
        dpi,
        pixelBuffer.ToArray());

    await encoder.FlushAsync();
}

The compile-time err msgs I get is about IRandomAccessStream:

1>C:\Users\bclay\source\repos\MyMaps\MyMaps\Form1.cs(394,78,394,97): error CS0246: The type or namespace name 'IRandomAccessStream' could not be found (are you missing a using directive or an assembly reference?)

So I found this, which indicates the "using" I need is using Windows.Storage.Streams;

...but when I add that, I am told that the "Windows" namespace cannot be found:

1>C:\Users\bclay\source\repos\MyMaps\MyMaps\Form1.cs(8,7,8,14): error CS0246: The type or namespace name 'Windows' could not be found (are you missing a using directive or an assembly reference?)

What do I need to do/change/add to get this to work on Winforms? Or is a totally different approach needed in my case?

Upvotes: 0

Views: 440

Answers (1)

Reza Aghaei
Reza Aghaei

Reputation: 125277

There are several ways to do it.

As an easy (but definitely not a perfect) option, you can use Graphics.FromScreen to copy a piece of screen to the graphics object:

var r = elementHost1.ClientRectangle;
using (var img = new Bitmap(r.Width, r.Height))
{
    using (var g = Graphics.FromImage(img))
    {
        var sr = elementHost1.RectangleToScreen(r);
        g.CopyFromScreen(sr.Location, System.Drawing.Point.Empty, sr.Size);
    }
    System.Windows.Forms.Clipboard.SetImage(img);
}

Another option is using RenderTargetBitmap and PngBitmapEncoder to export it to image like this:

public System.Drawing.Image DrawToImage(
    System.Windows.Controls.Control target)
{
    var rtb = new System.Windows.Media.Imaging.RenderTargetBitmap(
        (int)(target.ActualWidth), (int)(target.ActualHeight),
            96, 96, System.Windows.Media.PixelFormats.Pbgra32);
    rtb.Render(target);
    System.Windows.Media.Imaging.PngBitmapEncoder encoder =
        new System.Windows.Media.Imaging.PngBitmapEncoder();
    encoder.Frames.Add(System.Windows.Media.Imaging.BitmapFrame.Create(rtb));
    var ms = new System.IO.MemoryStream();
    encoder.Save(ms);
    return System.Drawing.Image.FromStream(ms);
}

Then you can set it into the clipboard:

using (var image = DrawToImage(userControl11.myMap))
    System.Windows.Forms.Clipboard.SetImage(image);

Or save it to a file:

using (var image = DrawToImage(userControl11.myMap))
    image.Save(@"c:\test\map.png", System.Drawing.Imaging.ImageFormat.Png);

Upvotes: 1

Related Questions