How to use Drawtobitmap in WPF to take screen print?

Asked

Viewed 162 times

0

Follows functional code of the WinForms:

Bitmap pic = new Bitmap(label1.Width, label1.Height);
Rectangle rect = new Rectangle(0, 0, label1.Width, label1.Height);
rect = label1.ClientRectangle;
label1.DrawToBitmap(pic, rect);
// pic.Save("C:\\, ImageFormat.Jpeg);

The above code strip printscreen of the label1 and save the image in place.

How do I do the same thing WinForms for WPF ?

Follow the attempt code of WPF:

Rect bounds = VisualTreeHelper.GetDescendantBounds(label1);

RenderTargetBitmap renderTarget = new RenderTargetBitmap((Int32)bounds.Width, (Int32)bounds.Height, 96, 96, PixelFormats.Pbgra32);

DrawingVisual visual = new DrawingVisual();

using (DrawingContext context = visual.RenderOpen())
{
    VisualBrush visualBrush = new VisualBrush(label1);
    context.DrawRectangle(visualBrush, null, new Rect(new System.Windows.Point(), bounds.Size));
}

renderTarget.Render(visual);
PngBitmapEncoder bitmapEncoder = new PngBitmapEncoder();
bitmapEncoder.Frames.Add(BitmapFrame.Create(renderTarget));

using (Stream stm = File.Create(@"C:\Users\Matheus Miranda\Desktop\TESTE"))
{
    bitmapEncoder.Save(stm);
}

Some solution ?

  • 1

    https://social.msdn.microsoft.com/Forums/vstudio/en-US/df4db537-a201-4ab4-bb7e-db38a5c2b6e0/wpf-equivalent-of-winforms-controldrawtobitmap?forum=wpf

  • 1

    I just solved problem: change this @"C:\Users\Matheus Miranda\Desktop\TESTE" for @"C:\Users\Matheus Miranda\Desktop\TESTE"\nomedafoto.jpg

  • @Rovannlinhalis You know how to make the image high quality ?

  • 1

    not man... nor do I mess with wpf =/, I just tried to help with the link there

  • 1

    It would be interesting to post an answer so the question is not pending.

1 answer

0


Problem solved:

Exchange that line @"C:\Users\Matheus Miranda\Desktop\TESTE" for @"C:\Users\Matheus Miranda\Desktop\TESTE"\nomedafoto.jpg

I forgot to specify file name.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.