Microsoft Communities

Welcome to WindowsClient.net | Sign in | Join

Here are some frequently asked questions about Windows Forms and their answers.

Windows Forms FAQs

How do I capture a bitmap of a form?

You can P/Invoke the BitBlt function from gdi32.dll to handle this problem.

using System;
using System.Drawing;
using System.Drawing.Imaging;
using System.Runtime.InteropServices;
using System.Windows.Forms;

class CustomForm : Form
{
  [ DllImport( "gdi32.dll" ) ] 
  private static extern bool BitBlt( IntPtr hdcDest, int nXDest, int nYDest,
    int nWidth, int nHeight, IntPtr hdcSrc, int nXSrc, int nYSrc, Int32 dwRop );

  private const Int32 SRCCOPY = 0xCC0020;

  public void SaveImage( string filename )
  {
    using ( Graphics g1 = CreateGraphics() )
    {
      Image image = 
        new Bitmap( ClientRectangle.Width, ClientRectangle.Height, g1 ); 
      using ( Graphics g2 = Graphics.FromImage( image ) )
      {
        IntPtr dc1 = g1.GetHdc(); 
        IntPtr dc2 = g2.GetHdc(); 
        BitBlt( dc2, 0, 0, ClientRectangle.Width, ClientRectangle.Height,
          dc1, 0, 0, SRCCOPY ); 
        g2.ReleaseHdc( dc2 ); 
        g1.ReleaseHdc( dc1 ); 
      }
      image.Save( filename, ImageFormat.Bmp ); 
    }
  }
}

Simon Murrell, and Lion Shi



Page view counter