C# WPF - How to Save a Screenshot of your Program's Interface's Current View?

704 views Asked by At

I am trying to have an option in my program called 'Save Current Snapshot', where a picture of my program's interface is saved to a desired location. This is for reference purposes, e.g. if someone doesn't want to open the program to see a result they've already gathered.

I already have a program screenshot function, I just don't know how to implement it with a SaveFileDialog to save the image.

Screenshot function:

private static BitmapSource CopyScreen()
        {
            using (var screenBmp = new Bitmap(
                (int)SystemParameters.PrimaryScreenWidth,
                (int)SystemParameters.PrimaryScreenHeight,
                System.Drawing.Imaging.PixelFormat.Format32bppArgb))
            {
                using (var bmpGraphics = Graphics.FromImage(screenBmp))
                {
                    bmpGraphics.CopyFromScreen(0, 0, 0, 0, screenBmp.Size);
                    return Imaging.CreateBitmapSourceFromHBitmap(
                        screenBmp.GetHbitmap(),
                        IntPtr.Zero,
                        Int32Rect.Empty,
                        BitmapSizeOptions.FromEmptyOptions());
                }
            }
        }

SaveFileDialog code:

SaveFileDialog saveImage = new SaveFileDialog();
saveImage.Filter = "Images|*.png;*.bmp;*.jpg";
saveImage.ShowDialog();

Could someone please help me out with saving the image to a user-chosen location? Thanks.

1

There are 1 answers

0
Yitzchak On

You can use the referenced code in the comment.

Use the save dialog to get the desired path and do just like commented by @Zack

// If the file name is not an empty string open it for saving.
if(saveImage.FileName != "")
{
    System.IO.FileStream fs = System.IO.File.Open(saveImage.FileName, System.IO.FileMode.OpenOrCreate);
    Screenshot.Save(fs, System.Drawing.Imaging.ImageFormat.Bmp);
    fs.Close();
}

I'm on the phone so can't check this, comment if you have problems