I am currently migrating an old Winforms project to WPF with the MVVM pattern, so I have been strugling with a lot of things. One on the last things I need to understand is how to do a screen capture of the application Window after a SaveDialog Close. On Winforms is easy and I have the following code that does the job:
Form frm = Form.ActiveForm;
if (frm != null)
{
using (Bitmap bmp = new Bitmap(frm.Width, frm.Height))
{
frm.DrawToBitmap(bmp, new Rectangle(0, 0, bmp.Width, bmp.Height));
bmp.Save(saveFileDialog.FileName, ImageFormat.Png);
}
}
I have been struggling a lot with this and I have found something equivalent on WPF:
double screenLeft = SystemParameters.VirtualScreenLeft;
double screenTop = SystemParameters.VirtualScreenTop;
double screenWidth = SystemParameters.VirtualScreenWidth;
double screenHeight = SystemParameters.VirtualScreenHeight;
using (Bitmap bmp = new Bitmap((int)screenWidth, (int)screenHeight))
{
using (Graphics g = Graphics.FromImage(bmp))
{
g.CopyFromScreen((int)screenLeft, (int)screenTop, 0, 0, bmp.Size);
bmp.Save(nombreArchivo);
}
}
The problem with the past code is the following: -First it creates a picture of the Whole screen. -Second it give me ghosting results as soon as the SaveDialog close.
I just ask a way of how to do it as simple as Winforms using Form.ActiveForm;
or the equivalent on WPF which I can't find.
Thanks in advance.
EDIT: Even if is marked as duplicated, none of the "duplicated" questions satisfied my needs, but I finally realized how to do it in a similar way of Winforms (simple), in case anyone needs it.
Window? window = Application.Current.Windows.OfType<Window>().SingleOrDefault(x => x.IsActive);
if (window != null)
{
//Render Bitmap for Width and Height of window
RenderTargetBitmap renderTargetBitmap = new RenderTargetBitmap((int)window.ActualWidth, (int)window.ActualHeight, 96, 96, Pixelwindowats.Pbgra32);
renderTargetBitmap.Render(window);
//Define encoder png
PngBitmapEncoder png = new PngBitmapEncoder();
png.Frames.Add(BitmapFrame.Create(renderTargetBitmap));
using (Stream stm = File.Create(nombreArchivo))
{
png.Save(stm);
}
}