Screenshot your WPF application



Often we need a way to capture picture of UI. For example if error occurs in our application we can take picture of UI and send this picture in error report.

Usual way in windows forms is calling Graphic.CopyFromScreen method. This way is not work very well in WPF. If we have some transparent controls on form this method will save image under transparent control.

So in WPF we will use GDI+ to take picture of UI. We have internal class NativeMethods:

 internal class NativeMethods

    {

        [DllImport(“user32.dll”)]

        public extern static IntPtr GetDesktopWindow();

        [System.Runtime.InteropServices.DllImport(“user32.dll”)]

        public static extern IntPtr GetWindowDC(IntPtr hwnd);

        [DllImport(“user32.dll”, CharSet = CharSet.Auto, ExactSpelling = true)]

        public static extern IntPtr GetForegroundWindow();

        [System.Runtime.InteropServices.DllImport(“gdi32.dll”)]

        public static extern UInt64 BitBlt

             (IntPtr hDestDC,

             int x,

             int y,

             int nWidth,

             int nHeight,

             IntPtr hSrcDC,

             int xSrc,

             int ySrc,

             System.Int32 dwRop);

    }

And we take picture UI by calling this method :

 public void SaveScreen()

        {

            Bitmap myImage = new Bitmap(Screen.PrimaryScreen.WorkingArea.Width,

            Screen.PrimaryScreen.WorkingArea.Height);

            Graphics gr1 = Graphics.FromImage(myImage);

            IntPtr dc1 = gr1.GetHdc();

            IntPtr dc2 = NativeMethods.GetWindowDC(NativeMethods.GetForegroundWindow());

            NativeMethods.BitBlt(dc1, Screen.PrimaryScreen.Bounds.X, Screen.PrimaryScreen.Bounds.Y, Screen.PrimaryScreen.Bounds.Width,

                 Screen.PrimaryScreen.Bounds.Height, dc2, 0, 0, 13369376);

            gr1.ReleaseHdc(dc1);

            myImage.Save(“screen.png”, ImageFormat.Png);

        }

 

 

  • Khumara

    Is it possible to get the resources out of the WPF dialog at the same time?

  • http://blog.developers.ba/ admin

    I am not sure what are you asking Khumara?

  • waaahsabi

    Unfortunately, the method described here has absolutely NOTHING to do with WPF whatsoever. This uses the System.Drawing namespace, as opposed to WPF's System.Windows.Media.Imaging namespace. Screen grabbing with this method will not work reliably from within, ex., a Windows Service.