Recording Visualbrush UiElement WPF

Apr 19, 2015 at 5:38 PM
Hi All,

From the Sample project Screen Capture I needed to capture a UiElement in WPF as this is my output in case it my help others I made this change in the GetScreenshot Method it seems to work ok there maybe a better way to do it !
m.Dispatcher.BeginInvoke(DispatcherPriority.Background, new Action(delegate
        {
            double actualHeight = m.RenderSize.Height;
            double actualWidth = m.RenderSize.Width;

            double renderHeight = actualHeight * 1.0;
            double renderWidth = actualWidth * 1.0;


              System.Windows.Media.Imaging.RenderTargetBitmap targetBitmap =
      new System.Windows.Media.Imaging.RenderTargetBitmap((int)screenWidth,
                                                          (int)screenHeight,
                                                          96, 96,
                                                          System.Windows.Media.PixelFormats.Pbgra32);



              VisualBrush sourceBrush = new VisualBrush(m);



              DrawingVisual drawingVisual = new DrawingVisual();
              DrawingContext drawingContext = drawingVisual.RenderOpen();

              using (drawingContext)
              {
                  drawingContext.PushTransform(new ScaleTransform(1.0, 1.0));
                  drawingContext.DrawRectangle(sourceBrush, null, new Rect(new System.Windows.Point(0, 0), new System.Windows.Point(actualWidth, actualHeight)));
              }
              targetBitmap.Render(drawingVisual);





              var bitmap = new Bitmap(targetBitmap.PixelWidth, targetBitmap.PixelHeight,
  System.Drawing.Imaging.PixelFormat.Format32bppPArgb);

              var bitmapData = bitmap.LockBits(new System.Drawing.Rectangle(System.Drawing.Point.Empty, bitmap.Size),
                  ImageLockMode.ReadOnly, System.Drawing.Imaging.PixelFormat.Format32bppRgb);

              targetBitmap.CopyPixels(Int32Rect.Empty, bitmapData.Scan0,
                  bitmapData.Stride * bitmapData.Height, bitmapData.Stride);
            screenHeight), ImageLockMode.ReadOnly, System.Drawing.Imaging.PixelFormat.Format32bppRgb);
              Marshal.Copy(bitmapData.Scan0, buffer, 0, buffer.Length);
              bitmap.UnlockBits(bitmapData);

              bitmap.Dispose();
          }));