我的简单目标是截取屏幕截图。 我的应用程序有一个主窗口,有多个用途,其中一个是截图。
我所做的是使用MainWindow.Hide();
隐藏窗口,然后显示处理屏幕截图处理过程的第二个窗口。
this.Hide();
SnapshotManager snapshotMgr = new SnapshotManager();
snapshotMgr.Closed += SnapshotMgrClosed;
snapshotMgr.Show();
第二个窗口基本上是这样的:
<Grid>
<Image Name="MainImage" Stretch="None" HorizontalAlignment="Stretch" VerticalAlignment="Stretch">
</Image>
<Border BorderBrush="Transparent" BorderThickness="0" HorizontalAlignment="Stretch" VerticalAlignment="Stretch">
<Border.Background>
<SolidColorBrush Color="Black" Opacity="0.4"/>
</Border.Background>
</Border>
</Grid>
具有属性:
AllowsTransparency="True"
Background="Transparent"
WindowStyle="None"
当用户点击按钮拍摄屏幕截图时,我会隐藏主窗口并显示此窗口。 然后我将屏幕保存到第二个窗口中的图像,如下所示:
Bitmap snapshot = new Bitmap(Screen.PrimaryScreen.Bounds.Width, Screen.PrimaryScreen.Bounds.Height);
Graphics graphics = Graphics.FromImage(snapshot);
graphics.CopyFromScreen(new System.Drawing.Point(0,0), new System.Drawing.Point(0,0), Screen.PrimaryScreen.Bounds.Size, CopyPixelOperation.SourceCopy);
//-----------------------------------
// Save the screen to MainImage
//-----------------------------------
MemoryStream ms = new MemoryStream();
snapshot.Save(ms, ImageFormat.Bmp);
ms.Position = 0;
BitmapImage bi = new BitmapImage();
bi.BeginInit();
bi.StreamSource = ms;
bi.EndInit();
MainImage.Source = bi;
问题是由于某种原因我的主窗口出现在屏幕截图中。 MainWindow.Hide()可能不像我想的那样工作。 如何使用主窗口截取屏幕截图?
谢谢!
编辑: 以下代码可以使用Sleep(200),我真的很想避免。
private void OnTakeSnapshot(object sender, RoutedEventArgs e)
{
this.LayoutUpdated += RunSnapshotMgr;
this.Hide();
}
private void RunSnapshotMgr(object sender, EventArgs e)
{
if (IsVisible == true) return;
Thread.Sleep(200);
SnapshotManager snapshotMgr = new SnapshotManager();
snapshotMgr.Closed += SnapshotMgrClosed;
snapshotMgr.Show();
this.LayoutUpdated -= RunSnapshotMgr;
}