当我按下窗口上的按钮时,我想截取屏幕截图。问题是,在截取屏幕截图之前窗口会消失。
这是我的代码:
主窗口:
private void OnButtonScreenshotClick(object sender, RoutedEventArgs routedEventArgs)
{
this.Visibility = Visibility.Hidden;
ScreenCapture capture = new ScreenCapture();
this.Close();
capture.Show();
}
ScreenCapture(显示屏幕截图)
public ScreenCapture()
{
InitializeComponent();
this.ScreenCaptureImage.Source = Screenshot.TakeFullScreenshot(width, height);
}
正如您所见,我在初始化新的ScreenCapture-Window之前尝试隐藏窗口。我也尝试使用Thread.Sleep延迟,但这也不起作用。
这是我拍摄屏幕截图的代码:
public static ImageSource TakeFullScreenshot(int width, int height)
{
Image bitmap = new Bitmap(width, height);
{
using (Graphics graphics = Graphics.FromImage(bitmap))
{
graphics.CopyFromScreen(new Point(0, 0), new Point(0, 0), bitmap.Size);
}
}
return GetImageStream(bitmap);
}
private static BitmapSource GetImageStream(Image myImage)
{
var bitmap = new Bitmap(myImage);
IntPtr bmpPt = bitmap.GetHbitmap();
BitmapSource bitmapSource =
System.Windows.Interop.Imaging.CreateBitmapSourceFromHBitmap(
bmpPt,
IntPtr.Zero,
Int32Rect.Empty,
BitmapSizeOptions.FromEmptyOptions());
//freeze bitmapSource and clear memory to avoid memory leaks
//bitmapSource.Freeze();
//DeleteObject(bmpPt);
return bitmapSource;
}
有什么建议吗?
答案 0 :(得分:3)
使用this而不是this.Close();
this.Hide();