LoginSignup
0
0

More than 5 years have passed since last update.

コントロールをGraphicsへ描画

Posted at

DataGridViewではCellにUserContorlを表示することができない。
なら、DataGridViewColumnにUserControlを持たせておき、
そのUserControlを利用して描画すればよいのではないか(-_-)

なので、Control.DrawToBitmapを参考流用して実現してみた。

CaptureControl.cs
public class CaptureControl
{
    [DllImport("user32.dll", CharSet = CharSet.Auto)]
    private static extern IntPtr SendMessage(HandleRef hWnd, int msg, IntPtr wParam, IntPtr lParam);
    [DllImport("gdi32.dll", CharSet = CharSet.Auto, ExactSpelling = true, SetLastError = true)]
    private static extern bool BitBlt(HandleRef hDC, int x, int y, int nWidth, int nHeight, HandleRef hSrcDC, int xSrc, int ySrc, int dwRop);

    public static void Capture(Graphics graphics, Control control, Rectangle rect)
    {
        int width = Math.Min(rect.Width, control.Width);
        int height = Math.Min(rect.Height, control.Height);
        using (var image = new Bitmap(width, height))
        using (Graphics sourceGraphics = Graphics.FromImage(image))
        {
            var sourceHdc = sourceGraphics.GetHdc();
            SendMessage(new HandleRef(control, control.Handle), 791, sourceHdc, (IntPtr)30);
            IntPtr hdc2 = graphics.GetHdc();
            BitBlt(new HandleRef(graphics, hdc2), 0, 0, width, height, new HandleRef(sourceGraphics, sourceHdc), 0, 0, 13369376);
            graphics.ReleaseHdcInternal(hdc2);
            sourceGraphics.ReleaseHdcInternal(sourceHdc);
        }
    }
}

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0