why does the Control.DrawToBitmap changes the pixelformat to DontCare?

829 views Asked by At

I used IlSpy to investigate the method it turned out to be designed to preserve the pixel format of the target bitmap here is the code:

public void DrawToBitmap(Bitmap bitmap, Rectangle targetBounds)
    {
        if (bitmap == null)
        {
            throw new ArgumentNullException("bitmap");
        }
        if (targetBounds.Width <= 0 || targetBounds.Height <= 0 || targetBounds.X < 0 || targetBounds.Y < 0)
        {
            throw new ArgumentException("targetBounds");
        }
        if (!this.IsHandleCreated)
        {
            this.CreateHandle();
        }
        int nWidth = Math.Min(this.Width, targetBounds.Width);
        int nHeight = Math.Min(this.Height, targetBounds.Height);
        Bitmap image = new Bitmap(nWidth, nHeight, bitmap.PixelFormat);
        using (Graphics graphics = Graphics.FromImage(image))
        {
            IntPtr hdc = graphics.GetHdc();
            UnsafeNativeMethods.SendMessage(new HandleRef(this, this.Handle), 791, hdc, (IntPtr)30);
            using (Graphics graphics2 = Graphics.FromImage(bitmap))
            {
                IntPtr hdc2 = graphics2.GetHdc();
                SafeNativeMethods.BitBlt(new HandleRef(graphics2, hdc2), targetBounds.X, targetBounds.Y, nWidth, nHeight, new HandleRef(graphics, hdc), 0, 0, 13369376);
                graphics2.ReleaseHdcInternal(hdc2);
            }
            graphics.ReleaseHdcInternal(hdc);
        }
    }

if you check the pixel format of "bitmap" at the very end of the method after the drawing it gives the right "Pixelformat" but once you check the bitmap on which you draw the control (the one passed to the method) it give "DontCare" pixelformat.

what is the reason behind this ?

0

There are 0 answers