I'm trying to use this code to draw a Bitmap
directly onto a PictureBox
:
Bitmap bmp = (Bitmap)Bitmap.FromFile(@"C:\Users\Ken\Desktop\Load2.bmp");
Graphics grDest = Graphics.FromHwnd(pictureBox1.Handle);
Graphics grSrc = Graphics.FromImage(bmp);
IntPtr hdcDest = grDest.GetHdc();
IntPtr hdcSrc = grSrc.GetHdc();
BitBlt(hdcDest, 0, 0, pictureBox1.Width, pictureBox1.Height,
hdcSrc, 0, 0, (uint)TernaryRasterOperations.SRCCOPY); // 0x00CC0020
grDest.ReleaseHdc(hdcDest);
grSrc.ReleaseHdc(hdcSrc);
but instead of rendering the Bitmap
's contents it just draws a solid block of nearly-black. I'm pretty sure the problem is with the source hDC, because if I change SRCCOPY to WHITENESS in the above code, it draws a solid white block, as expected.
Note: this next snippet works fine, so there's nothing wrong with the bitmap itself:
Bitmap bmp = (Bitmap)Bitmap.FromFile(@"C:\Users\Ken\Desktop\Load2.bmp");
pictureBox1.Image = bmp;
This is because a device context contains a 1x1 black bitmap until
SelectObject
is used. For whatever reason,Graphics.FromImage
is giving you a device context that is compatible with the bitmap, but it does not automatically select the bitmap into the device context.The following code will use
SelectObject
.You should, of course, use the managed
Graphics.DrawImage
instead ofBitBlt
if possible, but I assume that you have a good reason for usingBitBlt
.