Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

WPF: Take a screenshot and save it [duplicate]

Tags:

c#

wpf

I'm new to WPF applications and I've tried looking around to see if I could find something that works for this, but so far nothing I've found works (I guess it's because most of it is outdated). I want to take a screenshot of the entire desktop (i.e. all monitors) and save it as a .jpg to a specific folder with the time and date as the file name when I click the screenshot button. I was able to achieve this in my Windows Forms application, but haven't been able to do so with my WPF application.

This is the code that I used for my Windows Forms application.

int screenLeft = SystemInformation.VirtualScreen.Left;
int screenTop = SystemInformation.VirtualScreen.Top;
int screenWidth = SystemInformation.VirtualScreen.Width;
int screenHeight = SystemInformation.VirtualScreen.Height;

using (Bitmap bmp = new Bitmap(screenWidth, screenHeight))
{
    using (Graphics g = Graphics.FromImage(bmp))
    {
        String filename = "ScreenCapture-" + DateTime.Now.ToString("ddMMyyyy-hhmmss") + ".png";
        Opacity = .0;
        g.CopyFromScreen(screenLeft, screenTop, 0, 0, bmp.Size);
        bmp.Save("C:\\ScreenShots\\" + filename);
        Opacity = 1;
    }
}

Any help would be appreciated.

like image 843
Raya Avatar asked Jan 17 '16 10:01

Raya


1 Answers

In WPF project, you have to manually add reference to System.Drawing.dll library. To do so, Project > Add reference > Assembly tab (Framework) > check the desired library.

Moreover your code needs just a bit of tweaking, but the idea it's correct.

        double screenLeft = SystemParameters.VirtualScreenLeft;
        double screenTop = SystemParameters.VirtualScreenTop;
        double screenWidth = SystemParameters.VirtualScreenWidth;
        double screenHeight = SystemParameters.VirtualScreenHeight;

        using (Bitmap bmp = new Bitmap((int)screenWidth,
            (int)screenHeight))
        {
            using (Graphics g = Graphics.FromImage(bmp))
            {
                String filename = "ScreenCapture-" + DateTime.Now.ToString("ddMMyyyy-hhmmss") + ".png";
                Opacity = .0;
                g.CopyFromScreen((int)screenLeft, (int)screenTop, 0, 0, bmp.Size);
                bmp.Save("C:\\Screenshots\\" + filename);
                Opacity = 1;
            }

        }
like image 50
fillobotto Avatar answered Oct 05 '22 19:10

fillobotto