BitBlt code not working

I am trying to use this code to draw a Bitmap directly on 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 Bitmap content, it just draws a solid block of almost black. I'm sure the problem is with the hDC source, because if I changed SRCCOPY to WHITENESS in the above code, it draws a solid white block, as expected.

Note: this following snippet works fine, so there is nothing wrong with the bitmap itself:

 Bitmap bmp = (Bitmap)Bitmap.FromFile(@"C:\Users\Ken\Desktop\Load2.bmp"); pictureBox1.Image = bmp; 
+4
source share
1 answer

This is because the device context contains a 1x1 black raster map until SelectObject is used. For some reason, Graphics.FromImage provides you with a device context that is compatible with a bitmap, but it does not automatically select a bitmap in the device context.

The following code will use SelectObject .

Of course, you should use managed Graphics.DrawImage instead of BitBlt , but I assume you have a good reason for using BitBlt .

 private void Draw() { using (Bitmap bmp = (Bitmap)Bitmap.FromFile(@"C:\Jason\forest.jpg")) using (Graphics grDest = Graphics.FromHwnd(pictureBox1.Handle)) using (Graphics grSrc = Graphics.FromImage(bmp)) { IntPtr hdcDest = IntPtr.Zero; IntPtr hdcSrc = IntPtr.Zero; IntPtr hBitmap = IntPtr.Zero; IntPtr hOldObject = IntPtr.Zero; try { hdcDest = grDest.GetHdc(); hdcSrc = grSrc.GetHdc(); hBitmap = bmp.GetHbitmap(); hOldObject = SelectObject(hdcSrc, hBitmap); if (hOldObject == IntPtr.Zero) throw new Win32Exception(); if (!BitBlt(hdcDest, 0, 0, pictureBox1.Width, pictureBox1.Height, hdcSrc, 0, 0, 0x00CC0020U)) throw new Win32Exception(); } finally { if (hOldObject != IntPtr.Zero) SelectObject(hdcSrc, hOldObject); if (hBitmap != IntPtr.Zero) DeleteObject(hBitmap); if (hdcDest != IntPtr.Zero) grDest.ReleaseHdc(hdcDest); if (hdcSrc != IntPtr.Zero) grSrc.ReleaseHdc(hdcSrc); } } } [DllImport("gdi32.dll", EntryPoint = "SelectObject")] public static extern System.IntPtr SelectObject( [In()] System.IntPtr hdc, [In()] System.IntPtr h); [DllImport("gdi32.dll", EntryPoint = "DeleteObject")] [return: MarshalAs(UnmanagedType.Bool)] public static extern bool DeleteObject( [In()] System.IntPtr ho); [DllImport("gdi32.dll", EntryPoint = "BitBlt")] [return: MarshalAs(UnmanagedType.Bool)] public static extern bool BitBlt( [In()] System.IntPtr hdc, int x, int y, int cx, int cy, [In()] System.IntPtr hdcSrc, int x1, int y1, uint rop); 
+8
source

Source: https://habr.com/ru/post/1301911/


All Articles