我使用曾经BitBlt将屏幕截图保存到图像文件(.NET紧凑型框架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);

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

有帮助吗?

解决方案

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

此外 hb 是一个 Bitmap 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);
            }
        }
    }

其他提示

您的意思是这些线条吗?

    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(您希望绘制的)。

你确定 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);
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top