我想要捕获屏幕的图像,但是我的应用程序中有一些wpf控件我不想出现在屏幕截图中。使用下面的代码,隐藏的控件有时仍会出现在屏幕截图中。我如何确保不会发生这种情况?
Window window = new Window();
Button button = new Button();
void ShowWindow()
{
button.Content = "button";
button.ToolTip = "tooltip";
window.Content = button;
window.Show();
button.Click += new RoutedEventHandler(button_Click);
}
void button_Click(object sender, RoutedEventArgs e)
{
//Hide some controls and all tooltips in the window
ToolTipService.SetIsEnabled(window, false);
button.Visibility = Visibility.Hidden;
//Block until wpf renders
Application.Current.Dispatcher.Invoke(
System.Windows.Threading.DispatcherPriority.Background,
new System.Threading.ThreadStart(delegate { }));
//Take screenshot
Bitmap bmpScreenshot = new Bitmap(System.Windows.Forms.Screen.PrimaryScreen.Bounds.Width,
System.Windows.Forms.Screen.PrimaryScreen.Bounds.Height,
System.Drawing.Imaging.PixelFormat.Format32bppArgb);
Graphics gfxScreenshot = Graphics.FromImage(bmpScreenshot);
gfxScreenshot.CopyFromScreen(System.Windows.Forms.Screen.PrimaryScreen.Bounds.X,
System.Windows.Forms.Screen.PrimaryScreen.Bounds.Y,
0, 0,
System.Windows.Forms.Screen.PrimaryScreen.Bounds.Size,
CopyPixelOperation.SourceCopy);
bmpScreenshot.Save("Screenshot.png", ImageFormat.Png);
//Restore controls and tooltips
button.Visibility = Visibility.Visible;
ToolTipService.SetIsEnabled(window, true);
}
答案 0 :(得分:1)
尝试在调度程序上使用低优先级,但仍然不能保证(source)。
另外,根据我的理解,WPF在UI线程空闲(或长时间阻塞)之前不会启动渲染过程,因此您可能希望将调度阻塞和放置。实际后台线程中的快照代码(或让调度程序异步调用快照代码)。然后在快照线程完成后恢复按钮可见性。
答案 1 :(得分:0)
您是否尝试过将DispatcherPriority
设为Normal
而不是Background
?