我有一些代码可以收集与应用程序关联的所有窗口,将它们呈现为位图,并将它们存储在List<BitmapSource>
中,以便以后处理和处理。
我的问题是,如果窗口最小化,图像只是一个放大的工具栏,而不是整个窗口的图像。有没有办法确保我收集放大的窗口或者在我收集之前最大化所有窗口?
编辑:如果用户有一些最小化的话,我宁愿不最大化所有窗口只是为了获取屏幕。
以下是相关代码:
public static List<BitmapSource> RenderWindows()
{
var windows = Application.Current.Windows
.OfType<Window>()
.Where(x => x.GetType() != typeof(AskAQuestionDialog) & x.GetType() != typeof(SelectScreenShots));
var bitmaps = new List<BitmapSource>();
foreach (var window in windows)
{
var bitmap = new RenderTargetBitmap((int)window.Width, (int)window.Height, 96d, 96d, PixelFormats.Default);
bitmap.Render(window);
bitmaps.Add(bitmap);
}
return bitmaps;
}
答案 0 :(得分:1)
我使用以下功能获取所有应用程序窗口的“屏幕截图”(也可以使用最小化的窗口)
/// <summary>
/// Gets a JPG "screenshot" of the current UIElement
/// </summary>
/// <param name="source">UIElement to screenshot</param>
/// <param name="scale">Scale to render the screenshot</param>
/// <param name="quality">JPG Quality</param>
/// <returns>Byte array of JPG data</returns>
public static byte[] GetJpgImage(this UIElement source, double scale, int quality)
{
double actualHeight = source.RenderSize.Height;
double actualWidth = source.RenderSize.Width;
double renderHeight = actualHeight * scale;
double renderWidth = actualWidth * scale;
RenderTargetBitmap renderTarget = new RenderTargetBitmap((int)renderWidth, (int)renderHeight, 96, 96, PixelFormats.Pbgra32);
VisualBrush sourceBrush = new VisualBrush(source);
DrawingVisual drawingVisual = new DrawingVisual();
DrawingContext drawingContext = drawingVisual.RenderOpen();
using (drawingContext)
{
drawingContext.PushTransform(new ScaleTransform(scale, scale));
drawingContext.DrawRectangle(sourceBrush, null, new Rect(new Point(0, 0), new Point(actualWidth, actualHeight)));
}
renderTarget.Render(drawingVisual);
JpegBitmapEncoder jpgEncoder = new JpegBitmapEncoder();
jpgEncoder.QualityLevel = quality;
jpgEncoder.Frames.Add(BitmapFrame.Create(renderTarget));
byte[] imageArray;
using (MemoryStream outputStream = new MemoryStream())
{
jpgEncoder.Save(outputStream);
imageArray = outputStream.ToArray();
}
return imageArray;
}
获取图片列表
List<ImageSource> list = new List<ImageSource>();
WindowCollection collection = Application.Current.Windows;
TypeConverter tc = TypeDescriptor.GetConverter(typeof(ImageSource));
for (int i = 0; i < collection.Count; i++)
{
byte[] imgBytes = ScreenShot.GetJpgImage(collection[i], 1, 90);
ImageSource img = (ImageSource)tc.ConvertFrom(imgBytes);
list.Add(img);
}