9

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.

Bernard Vander Beken
  • 4,848
  • 5
  • 54
  • 76
Raya
  • 93
  • 1
  • 1
  • 3
  • WPF is a UI platform, it is not concerned with graphics operations intrinsic to the host operating system, that's what GDI is for (by way of `System.Drawing.*`), even though it doesn't use WPF's (abstracted) graphics model. – Dai Jan 17 '16 at 12:29

1 Answers1

15

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;
            }

        }
fillobotto
  • 3,698
  • 5
  • 34
  • 58