2012-11-11 14 views
0

我想通過使用獲取像下面的代碼一樣的DesktopWindow句柄來獲取特定區域。如何使用fromHdc方法創建位圖圖像?

[DllImport("user32.dll")] 
    static extern IntPtr GetDesktopWindow(); 

    [DllImport("user32.dll")] 
    static extern IntPtr GetDCEx(IntPtr hwnd, IntPtr hrgn, uint flags); 

    [DllImport("user32.dll")] 
    static extern IntPtr ReleaseDC(IntPtr hwnd, IntPtr hdc); 

    public void ScreenShot() 
    { 
     try 
     { 
      IntPtr hwnd = GetDesktopWindow(); 
      IntPtr hdc = GetDCEx(hwnd, IntPtr.Zero, 1027); 

      Point temp = new Point(40, 40); 
      Graphics g = Graphics.FromHdc(hdc); 
      Bitmap bitmap = new Bitmap(mPanel.Width, mPanel.Height, g); 

      g.CopyFromScreen(PointToScreen(temp) , PointToScreen(PictureBox.Location) , PictureBox.Size); 

}

此代碼實際工作,但我想獲得它從CopyFromScreen的工藝製作的複製圖像。我曾嘗試使用類似Graphics.FromImage(位圖)的代碼,但無法獲取我想要的圖像...我的意思是,複製圖像。 當我使用Graphics對象fromHdc時,我無法找到獲取位圖圖像的方法。 我必須使用DC ....有什麼合適的方法嗎?

回答

2

在這裏你錯了,你不需要獲取桌面句柄,CopyFromScreen會將現在屏幕上的任何內容複製到目標圖形,所以你需要從圖像創建圖形對象。 以下代碼創建屏幕左上角的500x500圖像。

public static void ScreenShot() 
{ 
    var destBitmap = new Bitmap(500, 500); 
    using (var destGraph = Graphics.FromImage(destBitmap)) 
    { 
     destGraph.CopyFromScreen(new Point(), new Point(), destBitmap.Size); 
    } 
    destBitmap.Save(@"c:\bla.png"); 
} 

如果你真的有HDC你需要使用的BitBlt從GDI32:

[DllImport("gdi32.dll")] 
public static extern bool BitBlt(IntPtr hdc, int nXDest, int nYDest, int nWidth, int nHeight, IntPtr hdcSrc, int nXSrc, int nYSrc, int dwRop); 
+0

謝謝您的回答雖然是有點晚gratitute(becoz林懶惰......)我的問題有已完全清除。 –

+1

我的回答是否有幫助,或者您是以其他方式解決的? (關閉它的問題) – Arthur

+0

(幫助吸血鬼...) – heltonbiker