2009-07-22 16 views
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); 
} 

回答

1

嘗試在調度程序上使用低優先級,但它仍然不是保證(source)。

另外,根據我的理解,WPF在UI線程空閒(或長時間阻塞)之前不會啓動呈現過程,因此您可能希望將調度阻塞&快照代碼放置在實際後臺線程中(或者讓調度員異步調用快照代碼)。然後在快照線程完成後恢復按鈕可見性。

0

你有沒有嘗試設置DispatcherPriorityNormal而非Background

+0

或渲染,而不是正常/背景 – 2009-07-22 15:31:14

+0

更改DispacherPriority似乎沒有幫助。我相信這條路線是通過強制處理更高優先級的所有行爲來實現的。所以爲了強制渲染,它需要比渲染更低的優先級。但是,即使將其更改爲最低優先級也不能解決問題。 – kova 2009-07-22 16:18:44