Linked In Twitter RSS

Screenshot your WPF application

3. September 2009  · Comments (3)

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

        }

 

You can download Demo application :

ScreenShotWPF.rar (38.14 kb)

Comments (3) -

Khumara
Khumara United States
10/7/2009 5:35:00 PM

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

admin
admin Bosnia and Herzegovina
10/13/2009 5:03:02 AM

I am not sure what are you asking Khumara?

waaahsabi
waaahsabi United States
11/1/2011 3:26:14 AM

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.

Pingbacks and trackbacks (2)+

Add comment

  Country flag

biuquote
  • Comment
  • Preview
Loading