因此,我试图通过将位图保存到流并将“源”设置为BitmapImage来向图像的源添加“屏幕快照”。
但是由于某些原因,Image控件只是黑色,所以什么也没显示。 为什么会这样?
//this.Hide();
//Create a black bitmap with the correct width and height and use it as a "Canvas" that we will
//be performing a bit-block transfer on. (Bitmap is mutable)
Bitmap printscreen = new Bitmap(Screen.PrimaryScreen.Bounds.Width,
Screen.PrimaryScreen.Bounds.Height);
//To perform a bit-block transfer we need the object to be a "Graphics" object.
Graphics g = Graphics.FromImage(printscreen);
//Perform the bit-block transfer and alter the image.
//Source being the screens pixels, and the destination is the black bitmap.
g.CopyFromScreen(0, 0, 0, 0, printscreen.Size);
//Create a temporary memory stream for the image.
using (MemoryStream mStream = new MemoryStream())
{
//Save the graphics object (image) in the memory stream. with a specified format.
printscreen.Save(mStream, ImageFormat.Bmp);
var ImageSource = new BitmapImage();
ImageSource.BeginInit();
ImageSource.StreamSource = mStream;
ImageSource.EndInit();
ImageBox.Source = ImageSource;
}
如您所见,我将Source属性设置为ImageSource,但它是黑色的。
WPF
<Window x:Class="eh.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:eh"
mc:Ignorable="d"
Title="MainWindow" Height="450" Loaded="MainWindow_OnLoaded" WindowStyle="None" ResizeMode="NoResize" Background="Black" WindowState="Maximized" WindowStartupLocation="Manual" Left="0" Top="0" Width="800">
<Grid>
<Image x:Name="ImageBox" HorizontalAlignment="Left" VerticalAlignment="Top" Height="1920" Width="1080"/>
</Grid>
</Window>
答案 0 :(得分:0)
我忘记添加CacheOption,所以我添加了
ImageSource.CacheOption = BitmapCacheOption.OnLoad;