views:

377

answers:

1

I have an app which uses some usercontrols. I want to take a thumbnail image of the usercontrols when they are loaded for use and add them to a flowlayout panel.

Where can I find information on making a thumbnail image of a usercontrol when it's loaded?

+1  A: 

I don't know of a way to do it before it has been displayed, but once it is on the screen you could use an approach like this:

private Image GetControlThumb(Control control, int thumbSize)
{
    Bitmap imgLarge = new Bitmap(control.Bounds.Width, control.Bounds.Height);
    using (Graphics g = Graphics.FromImage(imgLarge))
    {
        g.CopyFromScreen(
            control.Parent.PointToScreen(new Point(control.Left, control.Top)),
            new Point(0, 0),
            new Size(control.Bounds.Width, control.Bounds.Height));
    }


    Size size;
    if (control.Width > control.Height)
    {
        size = new Size(thumbSize, (int)(thumbSize * (float)control.Height / (float)control.Width));
    }
    else
    {
        size = new Size((int)(thumbSize * (float)control.Width / (float)control.Height), thumbSize);
    }
    Image imgSmall = imgLarge.GetThumbnailImage(size.Width, size.Height, new Image.GetThumbnailImageAbort(delegate { return false; }), IntPtr.Zero);
    imgLarge.Dispose();
    return imgSmall;

}

You can use it to get a thumbnail of any control, like this:

myPictureBox.Image = GetControlThumb(someControl, 100);
Fredrik Mörk
On a button click I am able to save the image to disk but on user control laod I get a white image, can I use the Paint()... I know this is called several times on a usercontrol
Saif Khan
what's the purpose of the Using block?
Saif Khan
The Graphics class implements IDisposable; the using block assures that the Dispose method is invoked so that the Graphics object can release resources.
Fredrik Mörk