Search code examples
c#screenshot

How to capture snap of window including title bar


below is my routine which works fine but the routine is not generating the image of window including title bar. so guide me what i need to change in code.

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

UPDATE

ur code works but some top left portion is not ok. so here i am uploading the image which i have generated using ur code. please have a look and tell me what i need to fix in the code. form width is not coming properly. thanks enter image description here

UPDATE

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

Solution

  • Simply get the height of the title bar and add it to the height of the area to be captured (and subtract it from the current top of the image - check the source below for the changes):

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