Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I take a screenshot of a Winforms control/form in C#?

I have a listview control that is on a winforms form. It fills the full screen but there are more items there than the screen can show.

How can I take a screenshot of the whole control as if I could display the whole contents of the listview on screen? So if the whole listview takes 1000 x 4000 pixels, then I want an image/bitmap of that size.

How do I do this? When I try printscreen, it only returns what's on the screen and anything outside the screen appears grey.

like image 230
Joan Venge Avatar asked Sep 29 '09 16:09

Joan Venge


1 Answers

Forms are controls, so you should be able to save the entire contents to a bitmap with something like:

var bm = new Bitmap(yourForm.Width, yourForm.Height);
yourForm.DrawToBitmap(bm, bm.Size);
bm.Save(@"c:\whatever.gif", ImageFormat.Gif);

Update

DrawToBitmap only draws what's on-screen. If you want to draw the entire contents of the list you must iterate through the list to find the size of the contents then draw each item. Something like:

var f = yourControl.Font;
var lineHeight = f.GetHeight();

// Find size of canvas
var s = new SizeF();
using (var g = yourControl.CreateGraphics())
{
    foreach (var item in yourListBox.Items)
    {
        s.Height += lineHeight ;
        var itemWidth = g.MeasureString(item.Text, f).Width;
        if (s.Width < itemWidth)
            s.Width = itemWidth;
    }

    if (s.Width < yourControl.Width)
         s.Width = yourControl.Width;
}

using( var canvas = new Bitmap(s) )
using( var g = Graphics.FromImage(canvas) )
{
    var pt = new PointF();
    foreach (var item in yourListBox.Items)
    {
        pt.Y += lineHeight ;
        g.DrawString(item.Text, f, Brushes.Black, pt);
    }

    canvas.Save(wherever);
}
like image 123
Dour High Arch Avatar answered Oct 27 '22 21:10

Dour High Arch