2011-09-19 101 views
0

我使用VB.NET,試圖捕捉屏幕的一部分,所以我發現在幾個地方的代碼來捕捉整個屏幕:Graphics.CopyFromScreen創建一個空白圖像

Dim screenSize = SystemInformation.PrimaryMonitorSize 
Dim bitmap = New Bitmap(screenSize.Width, screenSize.Height) 
Using g As Graphics = Graphics.FromImage(bitmap) 

    g.CopyFromScreen(New Point(0, 0), New Point(0, 0), screenSize) 

End Using 
bitmap.Save("c:\scratch\screenshot.png", System.Drawing.Imaging.ImageFormat.Png) 

這工作沒有錯誤拋出和文件創建成功,但生成的圖像是完全透明的(這是正確的大小) - 我錯過了什麼?

This question涉及同樣的錯誤,但解決方案是使用Win32的GDI,我要儘可能避免

+1

它適用於我。 – chrissie1

+0

@Matt你想捕捉什麼,CopyFromScreen不能在某些源(DirectX)上工作 – msarchet

+0

@msarchet _我想最終捕獲一個窗口,但我只是試圖捕獲一個屏幕來測試此時的概念。什麼是當CopyFromScreen不起作用的解決方法,我怎麼知道這不起作用? –

回答

0

我決定沿着最終打印屏幕選項去由於與CopyFromScreen方法的問題:

'declarations 
Private Const VK_SNAPSHOT As Integer = &H2C 

<DllImport("user32.dll")> 
Public Function keybd_event(ByVal key As Integer, ByVal dummy As Integer, ByVal flags As Integer, ByVal info As IntPtr) As IntPtr 
End Function 


'Usage 
Dim loopCount As Integer = 0 

Clipboard.Clear() 
keybd_event(VK_SNAPSHOT, 0, 0, IntPtr.Zero) 
Application.DoEvents() 

Do Until Clipboard.ContainsImage Or (loopCount > 10) 
    loopCount += 1 
    System.Threading.Thread.Sleep(100) 
    Application.DoEvents() 
Loop 

If Clipboard.ContainsImage Then 
    Return Clipboard.GetImage 
Else 
    Return Nothing 
End If