C#Bitblit从Bitmap到控件(Compact Framework)

时间:2010-01-13 16:29:24

标签: c# graphics windows-mobile bitblt

我曾使用BitBlt将屏幕截图保存到图像文件(.Net Compact Framework V3.5,Windows Mobile 2003及更高版本)。工作得很好。现在我想在表单中绘制一个位图。我可以使用this.CreateGraphics().DrawImage(mybitmap, 0, 0),但我想知道它是否可以像之前一样使用BitBlt而只是交换参数。所以我写道:

[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);

但表格保持白色。这是为什么?我提交的错误在哪里? 谢谢你的意见。干杯,大卫

3 个答案:

答案 0 :(得分:4)

this.Handle窗口句柄而不是设备上下文

this.Handle替换为this.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);
            }
        }
    }

答案 1 :(得分: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

编辑:这个片段并不是很清楚,但BitBlt中的hDC是目标位图的HDC(你想要绘制的)。

答案 2 :(得分: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);