3

我曾经使用 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);

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

4

3 回答 3

5

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

另外hbis a Bitmap Handlenot adevice 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);
            }
        }
    }
于 2010-01-13T17:08:26.313 回答
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);
    }

仅供参考,这就是SDF 的内容

编辑:在这个片段中并不是很清楚,但是 BitBlt 中的 hDC 是目标位图的 HDC(您希望在其中绘制)。

于 2010-01-13T16:49:06.743 回答
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);
于 2010-01-13T16:37:16.610 回答