下面是一个简单应用程序的代码,它在窗口的画布上绘制一个矩形,然后在按下任意键时使用 CopyFromScreen 函数截取应用程序的屏幕截图。然而,就在调用它之前,我调用了 canvas.Children.Clear()。然后,我希望生成的图像中没有矩形,但确实如此。似乎在调用函数时,实际的矩形图像并未从画布中删除,但在一段时间后。
我尝试放入 System.Threading.Thread.Sleep(1000); 在 Clear() 调用之后,但矩形也停留在屏幕上整整一秒。显然它在按键功能完成后被删除,有没有办法在 CopyFromScreen 调用之前删除它?
要运行它,您需要添加对 System.Drawing 的引用。
XAML 代码
<Window x:Class="CanvasTest.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Width="210" Height="240"
KeyDown="keyPressed">
<Window.Background>
<SolidColorBrush Color="White"/>
</Window.Background>
<Grid>
<Canvas Name="canvas"
HorizontalAlignment="Left" VerticalAlignment="Top">
</Canvas>
</Grid>
</Window>
.cs 代码
using System;
using System.ComponentModel;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Shapes;
namespace CanvasTest {
public partial class MainWindow : Window {
public MainWindow() {
InitializeComponent();
Left = 0;
Top = 0;
Rectangle rect = new Rectangle {
Stroke = System.Windows.Media.Brushes.Black,
StrokeThickness = 1,
Width = 100,
Height = 100
};
canvas.Children.Add(rect);
Canvas.SetLeft(rect, 50);
Canvas.SetTop(rect, 50);
}
private void keyPressed(object sender, System.Windows.Input.KeyEventArgs e) {
System.Drawing.Bitmap bitmap = new System.Drawing.Bitmap((int)Width, (int)Height);
System.Drawing.Graphics graphics = System.Drawing.Graphics.FromImage(bitmap);
canvas.Children.Clear();
graphics.CopyFromScreen(0, 0, 0, 0,
new System.Drawing.Size(bitmap.Width, bitmap.Height),
System.Drawing.CopyPixelOperation.SourceCopy);
String path = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
path += "\\MuckleEwesPic.png";
bitmap.Save(path, System.Drawing.Imaging.ImageFormat.Png);
}
}
}
如何清除画布然后截屏而不发生这种行为?并且没有“不添加矩形”不是解决方案哈,这只是发生问题的大型应用程序的一个最小示例。
谢谢。