如何在 C# 中截取 Winforms 控件/表单的屏幕截图? [英] How can I take a screenshot of a Winforms control/form in C#?

查看:35
本文介绍了如何在 C# 中截取 Winforms 控件/表单的屏幕截图?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个位于 winforms 表单上的 listview 控件.它填满了整个屏幕,但里面的项目比屏幕显示的要多.

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.

如何截取整个控件的屏幕截图,就好像我可以在屏幕上显示 listview 的全部内容一样?因此,如果整个 listview 需要 1000 x 4000 像素,那么我想要该大小的图像/位图.

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.

我该怎么做?当我尝试 printscreen 时,它只返回屏幕上的内容,屏幕外的任何内容都显示为灰色.

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

推荐答案

表单是控件,因此您应该能够将整个内容保存到位图,例如:

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);

更新

DrawToBitmap 只绘制屏幕上的内容.如果要绘制列表的全部内容,则必须遍历列表以找到内容的大小,然后绘制每个项目.类似的东西:

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);
}

这篇关于如何在 C# 中截取 Winforms 控件/表单的屏幕截图?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆