Handy Tool: Control Printer

This is one of my more recent controls I wrote. It will grab the screen image of a control/form onto an image and print it. I didn’t even need this but wrote it to help someone in a newgroup. Hope its helpfull to someone else:
public class ControlPrinter
{
	[ThreadStatic()]
	static Image _imgToPrint;
	[ThreadStatic()]
	static Point _locationOnPage;


	public static Image GetControlImage(Control c)
	{
		Graphics mygraphics = c.CreateGraphics();
		Image img = new Bitmap(c.Size.Width, c.Size.Height, mygraphics);

		Graphics memoryGraphics = Graphics.FromImage(img);


		IntPtr sourceHandle = mygraphics.GetHdc();
		IntPtr destinationHandle = memoryGraphics.GetHdc();

		BitBlt(destinationHandle,0,0, c.Width, c.Height, sourceHandle, 0, 0, 13369376);
		mygraphics.ReleaseHdc(sourceHandle);
		memoryGraphics.ReleaseHdc(destinationHandle);

		return img;

	}
	public static void PrintControl(Control c, Point locationOnPage)
	{
		PrintDocument pd = new PrintDocument();
		PrintPreviewDialog printPreviewDialog = new PrintPreviewDialog();
		printPreviewDialog.Document = pd;
		_locationOnPage = locationOnPage;
		pd.PrintPage += new PrintPageEventHandler(pd_PrintPage);
		Graphics mygraphics = c.CreateGraphics();
		_imgToPrint = GetControlImage(c);

		printPreviewDialog.ShowDialog();
	}

	static void pd_PrintPage(object sender, PrintPageEventArgs e)
	{
		e.Graphics.DrawImage(_imgToPrint, _locationOnPage);
	}



	[DllImport("gdi32.dll")]
	static extern bool BitBlt(IntPtr hdc, int nXDest, int nYDest, int nWidth, int nHeight, IntPtr hdcSrc, int nXSrc, int nYSrc, uint dwRop);
}


Advertisements
This entry was posted in Uncategorized. Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s