I used once BitBlt to save a screenshot to an image file (.Net Compact Framework V3.5, Windows Mobile 2003 and later). Worked fine. Now I want to draw a bitmap to a form. I could use this.CreateGraphics().DrawImage(mybitmap, 0, 0)
, but I was wondering if it would work with BitBlt like before and just swap the params. So I wrote:
[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);
(and further down:)
IntPtr hb = mybitmap.GetHbitmap();
BitBlt(this.Handle, 0, 0, mybitmap.Width, mybitmap.Height, hb, 0, 0, 0x00CC0020);
But the form stays plain white. Why is that? Where is the error I commited? Thanks for your opinions. Cheers, David
this.Handle
is a Window handle not a device context.
Replace this.Handle
with this.CreateGraphics().GetHdc()
Of course you'll need to destroy the graphics object etc...
IntPtr hb = mybitmap.GetHbitmap();
using (Graphics gfx = this.CreateGraphics())
{
BitBlt(gfx.GetHdc(), 0, 0, mybitmap.Width, mybitmap.Height, hb, 0, 0, 0x00CC0020);
}
In addition hb
is a Bitmap Handle
not a device context
so the above snippet still won't work. You'll need to create a device context from the bitmap:
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);
}
}
}