How to cache the image of the control?

822 views Asked by At

I have C# app, but the painting job is done within C++ project (this is how it has to be).

So I added to my window PictureBox, and passed the handle to the drawing function. It works fine.

However when the control is invalidated (I move the window outside the screen and then move it back), I get in result partially empty window. AFAIK there are two approaches for this -- repaint or cache the image.

Repainting could be costly process (the image does not change often, but processing is time consuming, think of 3d renderer), so I would like to simply cache the image.

If I remember correctly from old days of programming directly with Win32 API all it takes is to set some flags. Is it possible with WinForms? If yes, how?

1

There are 1 answers

2
TaW On BEST ANSWER

This will help:

Bitmap getControlSurface(Control ctl)
{
    bitmap = new Bitmap(ctl.Width, ctl.Height);

    using (Graphics g = Graphics.FromImage(bitmap))
    {
        Point pScreen = PointToScreen(ctl.Location);
        g.CopyFromScreen(pScreen, Point.Empty, ctl.Size);
    }
    return bitmap;
}

If you know when the surface has been refreshed you can use it like this:

 if ( pictureBox1.Image != null) pictureBox1.Image.Dispose();
 pictureBox1.Image =  getControlSurface(pictureBox1);

The only catch is that the PictureBox actually must be completely visible on the screen!