如何捕捉包含标题栏的窗口的快照

时间:2013-03-11 07:16:08

标签: c#

下面是我的例行程序,它工作正常,但例程没有生成窗口的图像,包括标题栏。所以引导我在代码中需要更改的内容。

protected override void WndProc(ref Message m)
{

            if (m.Msg == WM_COMMAND && m.WParam.ToInt32() == SC_MINIMIZE)
            {
                OnMinimize(EventArgs.Empty);
            }

            base.WndProc(ref m);
}

protected virtual void OnMinimize(EventArgs e)
{
    Rectangle r = this.RectangleToScreen(ClientRectangle);

    if (_lastSnapshot == null)
    {
        _lastSnapshot = new Bitmap(r.Width, r.Height);
    }

    using (Image windowImage = new Bitmap(r.Width, r.Height))
    using (Graphics windowGraphics = Graphics.FromImage(windowImage))
    using (Graphics tipGraphics = Graphics.FromImage(_lastSnapshot))
    {
        windowGraphics.CopyFromScreen(new Point(r.Left, r.Top), new Point(0, 0), new Size(r.Width, r.Height));
        windowGraphics.Flush();

        tipGraphics.DrawImage(windowImage, 0, 0, r.Width, r.Height);
    }
}

更新

你的代码有效,但有些左上角部分不行。所以我在这里上传使用你的代码生成的图像。请看一下,告诉我在代码中需要修复的内容。表格宽度不正确。谢谢 enter image description here

更新

    Bitmap bmp = new Bitmap(this.Width, this.Height);
    this.DrawToBitmap(bmp, new Rectangle(Point.Empty, bmp.Size));
    bmp.Save(@"d:\Zapps.bmp", ImageFormat.Bmp);

1 个答案:

答案 0 :(得分:0)

只需获取标题栏的高度并将其添加到要捕获的区域的高度(并从图像的当前顶部减去它 - 请查看下面的源代码以了解更改):

protected virtual void OnMinimize(EventArgs e)
{
    Rectangle r = this.RectangleToScreen(this.ClientRectangle);
    int titleHeight = r.Top - this.Top;

    _lastSnapshot = new Bitmap(r.Width, r.Height);

    using (Image windowImage = new Bitmap(r.Width, r.Height + titleHeight))
    using (Graphics windowGraphics = Graphics.FromImage(windowImage))
    using (Graphics tipGraphics = Graphics.FromImage(_lastSnapshot))
    {
        windowGraphics.CopyFromScreen(new Point(r.Left, r.Top - titleHeight),
                 new Point(0, 0), new Size(r.Width, r.Height + titleHeight));
        windowGraphics.Flush();

        tipGraphics.DrawImage(windowImage, 0, 0, r.Width, r.Height + titleHeight);
        _lastSnapshot.Save(@".\tmp.bmp", ImageFormat.Bmp);
    }
}