適用範圍:微軟的WPF框架
好處:只針對指定視窗或UI元件截圖,不像Print Screen全螢幕可能會截到客戶的隱私,也比Alt+Print Screen使用上更有彈性
原始碼參考出處:
稍微調整,增加支援的圖檔格式:
BMP (System.Windows.Media.Imaging.BmpBitmapEncoder)
Gif (System.Windows.Media.Imaging.GifBitmapEncoder)
Jpeg (System.Windows.Media.Imaging.JpegBitmapEncoder)
PNG (System.Windows.Media.Imaging.PngBitmapEncoder)
Tiff (System.Windows.Media.Imaging.TiffBitmapEncoder)
WMP (System.Windows.Media.Imaging.WmpBitmapEncoder)
調整後原始碼:
ButtonLoginUser.ScreenshotToFile<PngBitmapEncoder>($"{DateTime.Now:yyMMdd_HHmmss}_{nameof(ButtonLoginUser)}.png");
public static void ScreenshotToFile<T>(this Visual obj, string fileName) where T : BitmapEncoder, new ()
{
DrawingVisual visual = new DrawingVisual();
Rect bounds = VisualTreeHelper.GetDescendantBounds(obj);
using (DrawingContext context = visual.RenderOpen())
{
context.DrawRectangle(new VisualBrush(obj), null, new Rect(new Point(), bounds.Size));
}
RenderTargetBitmap renderTarget = new RenderTargetBitmap((int)bounds.Width, (int)bounds.Height, 96, 96, PixelFormats.Pbgra32);
renderTarget.Render(visual);
T bitmapEncoder = new T();
bitmapEncoder.Frames.Add(BitmapFrame.Create(renderTarget));
FileInfo fInfo = new FileInfo(fileName);
fInfo.Directory.Create();
using (Stream stm = File.Create(fInfo.FullName))
{
bitmapEncoder.Save(stm);
}
}