2013-07-20 45 views
0

我用下面的代碼獲取截圖:WPF - 黑屏而非截圖

public static BitmapSource ToBitmapSource() 
    { 
     using (var screenBmp = new Bitmap(Convert.ToInt32(System.Windows.SystemParameters.PrimaryScreenWidth), 
      Convert.ToInt32(System.Windows.SystemParameters.PrimaryScreenHeight), 
      System.Drawing.Imaging.PixelFormat.Format32bppArgb)) 
     { 
      using (var bmpGraphics = Graphics.FromImage(screenBmp)) 
      { 
       bmpGraphics.CopyFromScreen(0, 0, 0, 
        0, screenBmp.Size); 
       return Imaging.CreateBitmapSourceFromHBitmap(screenBmp.GetHbitmap(), IntPtr.Zero, Int32Rect.Empty, BitmapSizeOptions.FromEmptyOptions()); 
      } 
     } 
    } 

它正常工作,正常的窗口,但我得到的全屏應用程序,而不是截圖黑色矩形。爲什麼以及如何解決? 謝謝

+0

你的意思是窗口在最大化狀態,當你黑的截圖? – Nitesh

+0

不,我的意思是FullScreen,就像遊戲 –

+0

那麼是不是你爲我工作的代碼,我張貼在我的答案? – Nitesh

回答

1

您提供的代碼是準確的。我認爲在保存屏幕截圖時遇到問題。所以我在這裏附上我的測試結果

private void Button_Click(object sender, RoutedEventArgs e) 
{ 
    PngBitmapEncoder png = new PngBitmapEncoder(); 
    png.Frames.Add(BitmapFrame.Create(ToBitmapSource())); // Calling your method 
    using (Stream stm = File.Create(AppDomain.CurrentDomain.BaseDirectory + "screenshot.png")) 
    { 
     png.Save(stm); 
    } 
} 

enter image description here