wpf 通过下面的截图,标题可能会丢失。
public void CreateBitmapFromVisual(Window win, string fileName)
{
if (win == null || string.IsNullOrEmpty(fileName))
{
return;
}
int index = fileName.LastIndexOf(System.IO.Path.DirectorySeparatorChar);
if (index > 0)
{
string tmpPath = fileName.Substring(0, index);
if (!Directory.Exists(tmpPath))
{
Directory.CreateDirectory(tmpPath);
}
}
RenderTargetBitmap renderTarget = new RenderTargetBitmap((Int32)win.Width, ((Int32)win.Height), 96, 96, PixelFormats.Pbgra32);
renderTarget.Render(win);
PngBitmapEncoder bitmapEncoder = new PngBitmapEncoder();
bitmapEncoder.Frames.Add(BitmapFrame.Create(renderTarget));
using (Stream stm = File.Create(fileName))
{
bitmapEncoder.Save(stm);
}
}
wpf 通过下面的截图,可能会截的多余或是少 的
public void CreateBitmapFromVisual(Window win, string fileName)
{
if (win == null || string.IsNullOrEmpty(fileName))
{
return;
}
int index = fileName.LastIndexOf(System.IO.Path.DirectorySeparatorChar);
if (index > 0)
{
string tmpPath = fileName.Substring(0, index);
if (!Directory.Exists(tmpPath))
{
Directory.CreateDirectory(tmpPath);
}
}
System.Drawing.Graphics graphics = System.Drawing.Graphics.FromHwnd(IntPtr.Zero);
float systemdpi = graphics.DpiX / 96;
var bitmap = new System.Drawing.Bitmap((int) (win.Width* systemdpi), (int)(win.Height* systemdpi), System.Drawing.Imaging.PixelFormat.Format32bppArgb);
using (System.Drawing.Graphics memoryGrahics = System.Drawing.Graphics.FromImage(bitmap))
{
memoryGrahics.CopyFromScreen((int)Math.Round(win.Left), (int)Math.Round(win.Top), 0, 0, new System.Drawing.Size((int)(win.Width* systemdpi), (int)(win.Height* systemdpi)), System.Drawing.CopyPixelOperation.SourceCopy);
}
bitmap.Save(fileName);
}
原因是 double 转化成 int ,造成位置信息错误,出现截图错误。神奇的 windows