Following is the functional code of 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 code above takes printscreen from label1
and saves the image in place.
How can I do the same from WinForms
to WPF
?
The attempt code of WPF
follows:
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);
}
Any solution?