2010-01-13 55 views
3

我用過一次的BitBlt到屏幕截圖保存爲圖像文件(.NET Compact Framework的V3.5的Windows Mobile 2003及更高版本)。工作很好。現在我想繪製一個位圖到一個窗體。我可以用this.CreateGraphics().DrawImage(mybitmap, 0, 0),但我想知道它是否會與BitBlt的工作像以前一樣,只是換了PARAMS。所以我寫了:從位圖C#象素數據控制(Compact Framework的)

[DllImport("coredll.dll")] 
public static extern int BitBlt(IntPtr hdcDest, int nXDest, int nYDest, int nWidth, int nHeight, IntPtr hdcSrc, int nXSrc, int nYSrc, uint dwRop); 

(進一步回落:)

IntPtr hb = mybitmap.GetHbitmap(); 
BitBlt(this.Handle, 0, 0, mybitmap.Width, mybitmap.Height, hb, 0, 0, 0x00CC0020); 

但形式保持純白色。這是爲什麼?我承諾的錯誤在哪裏? 感謝您的意見。歡呼聲中,大衛

回答

4

this.Handle窗口句柄不是設備上下文

更換this.Handlethis.CreateGraphics().GetHdc()

當然,你需要摧毀圖形對象等等......

IntPtr hb = mybitmap.GetHbitmap(); 
using (Graphics gfx = this.CreateGraphics()) 
{ 
    BitBlt(gfx.GetHdc(), 0, 0, mybitmap.Width, mybitmap.Height, hb, 0, 0, 0x00CC0020); 
} 

此外hbBitmap Handle不是device context所以上面的代碼中依然贏得」工作。您需要創建從位圖的設備上下文:

using (Bitmap myBitmap = new Bitmap("c:\test.bmp")) 
    { 
     using (Graphics gfxBitmap = Graphics.FromImage(myBitmap)) 
     { 
      using (Graphics gfxForm = this.CreateGraphics()) 
      { 
       IntPtr hdcForm = gfxForm.GetHdc(); 
       IntPtr hdcBitmap = gfxBitmap.GetHdc(); 
       BitBlt(hdcForm, 0, 0, myBitmap.Width, myBitmap.Height, hdcBitmap, 0, 0, 0x00CC0020); 
       gfxForm.ReleaseHdc(hdcForm); 
       gfxBitmap.ReleaseHdc(hdcBitmap); 
      } 
     } 
    } 
+0

一個小評論:)你不應該對HDC的你從兩個圖形對象得到調用ReleaseHdc()? – Matt 2010-01-14 06:45:29

0

你肯定this.Handle指的是有效的設備上下文?您是否嘗試過檢查BitBlt函數的返回值?

嘗試以下操作:

[DllImport("coredll.dll", EntryPoint="CreateCompatibleDC")] 
public static extern IntPtr CreateCompatibleDC(IntPtr hdc); 

[DllImport("coredll.dll", EntryPoint="GetDC")] 
public static extern IntPtr GetDC(IntPtr hwnd); 

IntPtr hdc  = GetDC(this.Handle); 
IntPtr hdcComp = CreateCompatibleDC(hdc); 

BitBlt(hdcComp, 0, 0, mybitmap.Width, mybitmap.Height, hb, 0, 0, 0x00CC0020); 
2

你的意思是沿着這些線路的東西嗎?

public void CopyFromScreen(int sourceX, int sourceY, int destinationX, 
           int destinationY, Size blockRegionSize, 
           CopyPixelOperation copyPixelOperation) 
    { 
     IntPtr desktopHwnd = GetDesktopWindow(); 
     if (desktopHwnd == IntPtr.Zero) 
     { 
      throw new System.ComponentModel.Win32Exception(); 
     } 
     IntPtr desktopDC = GetWindowDC(desktopHwnd); 
     if (desktopDC == IntPtr.Zero) 
     { 
      throw new System.ComponentModel.Win32Exception(); 
     } 
     if (!BitBlt(hDC, destinationX, destinationY, blockRegionSize.Width, 
      blockRegionSize.Height, desktopDC, sourceX, sourceY, 
      copyPixelOperation)) 
     { 
      throw new System.ComponentModel.Win32Exception(); 
     } 
     ReleaseDC(desktopHwnd, desktopDC); 
    } 

僅供參考,這是right out of the SDF

編輯:這不是在這個片段中真正清楚,但在的hDC的BitBlt的是目標位圖的HDC(爲您希望畫)。

相關問題