2010-01-13 37 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(为您希望画)。

相关问题