【问题标题】:How can I take a screenshot of a Winforms control/form in C#?如何在 C# 中截取 Winforms 控件/表单的屏幕截图?
【发布时间】:2010-12-02 09:22:02
【问题描述】:

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

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

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

【问题讨论】:

  • 您是尝试在代码中执行此操作,还是通过某种屏幕捕获工具?
  • 在代码中............

标签: c# .net winforms listview


【解决方案1】:

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

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

更新

DrawToBitmap 只绘制屏幕上的内容。如果要绘制列表的全部内容,则必须遍历列表以查找内容的大小,然后绘制每个项目。比如:

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

【讨论】:

  • 谢谢,我试过了,但位图显示为蓝色。我在listview而不是表单上尝试过,因为表单是固定的,但是listview有一个滚动条。
  • DrawToBitmap 绘制屏幕上的内容。您是否尝试在没有滚动条的情况下打印 ListView 的内容?您必须分别绘制每个项目。
  • 我明白了,现在我正在尝试打印整个内容,就好像你有一个无限大的显示器一样。我不在乎位图是否包含滚动条或其他任何内容,只要它将整个控件显示为位图即可。
【解决方案2】:

除非你不喜欢爆破,

Private Declare Function BitBlt Lib "gdi32" _
    (ByVal hDCDest As IntPtr, ByVal XDest As IntPtr, _
    ByVal YDest As IntPtr, ByVal nWidth As IntPtr, _
    ByVal nHeight As IntPtr, ByVal hDCSrc As IntPtr, _
    ByVal XSrc As IntPtr, ByVal YSrc As IntPtr, _
    ByVal dwRop As IntPtr) As IntPtr

Private Declare Function GetWindowDC Lib "user32" _
  (ByVal hWnd As IntPtr) As IntPtr

Private Declare Function ReleaseDC Lib "user32" _
  (ByVal hWnd As IntPtr, ByVal hdc As IntPtr) As IntPtr
Private Sub Blast()
    Dim dc As IntPtr
    dc = GetWindowDC(Me.Handle)
    Dim bm As Bitmap = New Bitmap(Me.Width, Me.Height)
    Dim g As Graphics = Graphics.FromImage(bm)
    Const vbSrcCopy = &HCC0020
    Dim gdc = g.GetHdc()
    BitBlt(gdc, 0, 0, Me.Width, Me.Height, dc, 0, 0, vbSrcCopy)
    g.ReleaseHdc()
    bm.Save("C:\yourfile.bmp", System.Drawing.Imaging.ImageFormat.Bmp)
    ReleaseDC(Me.Handle, dc)
End Sub

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-11-14
    • 2014-08-19
    • 1970-01-01
    • 2010-11-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多