1

我想捕获屏幕的图像,但是我的应用程序中有一些我不想出现在屏幕截图中的 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);
}
4

2 回答 2

1

尝试在调度程序上使用低优先级,但这仍然不是保证(source)。

另外,据我了解,WPF 直到 UI 线程空闲(或长时间阻塞)才开始渲染过程,因此您可能希望将调度阻塞和快照代码放在实际的后台线程中(或让调度程序异步调用快照代码)。然后在该快照线程完成后恢复按钮可见性。

于 2009-08-12T01:04:27.183 回答
0

您是否尝试过将其设置DispatcherPriorityNormal而不是Background

于 2009-07-22T15:28:41.847 回答