Blue Theme Orange Theme Green Theme Red Theme
 
Nevron Diagram
Home | Forums | Videos | Photos | Downloads | Blogs | Interviews | Jobs | Beginners | Training
 | Consulting  
Submit an Article Submit a Blog 
 Jump to
Skip Navigation Links
TechnologyExpand Technology
WebsiteExpand Website
Safari Books Online
 Resources  
Close
 Our Network  
Close
Search :       Advanced Search »
Home » Printing » How To: Printing Form Controls in C# and .NET

How To: Printing Form Controls in C# and .NET


The other day a user asked me how to print out a form. I suggested they use my Form Capture article which catches the bitmap that the form is in by using bit belting commands from the old windows SDK.

Author Rank:
Total page views :  73598
Total downloads :  2245
   Print Read/Post comments Post a comment  Similar Articles  
   Email to a friend  Bookmark  Author's other articles  
Download Files:
FormPrinting.zip
 
Become a Sponsor

The other day a user asked me how to print out a form.  I suggested they use my Form Capture article which catches the bitmap that the form is in by using bit belting commands from the old windows SDK.  It turns out this is not the ideal solution because it involves old Windows SDK code.  A better solution would be to draw the controls individually onto the printing graphics object.  But how the heck do I print a control?  Do I have to actually copy Microsoft Controls bit by bit?  Do I have to mimic the shading and 3d features by drawing different lines that produce shading effects?

Figure 1 - A Form and the Print Preview of the same Form

It turns out that Microsoft provides the user with a helpful class that allows us to draw these elusive controls called ControlPaint.  This class is more like an API containing a list of static methods to help you paint the controls.  Below I listed the ones used in this article and their purpose:

Method in ControlPaint Description
DrawButton Draws a Button in the Graphics area.  Note this command will not draw any text or image on the button 
DrawCheckBox Draws a Checkbox in the Graphics area 
DrawBorder3D This will allow you to draw any 3D Border Side.  

Table 1 - Methods of ControlPaint used in this article

As we have discussed in previous printing articles on C# Corner, printing and drawing are accomplished almost the same way, by writing to a device context, or in the case of .NET, to a Graphics Object.  We are not going to go into detail on how to set up the printing components for calling the method that paints the controls to the printer.  Please refer to Printing in C# on the site to see how to set up the Print_Page event handler.

Our event handler for printing the form will call a method called, ironically, DrawForm, and perform all of the control painting here. Below is the method DrawForm in our Form class:

Listing 1 - Draw the Form and controls to the printer Graphics object

void DrawForm(Graphics g, int resX, int resY)
{
g.FillRectangle(
new SolidBrush(this.BackColor), 0, 0, this.Width, this.Height);
float scale = resX/ScreenResolution;
// Cycle through each control on the form and paint it to the printe
foreach (Control c in Controls)
{
// Get the time of the next control so we can unbox it
string strType = c.GetType().ToString().Substring(c.GetType().ToString().LastIndexOf(".") + 1);
switch (strType)
{
case "Button": Button b = (Button)c;
// Use the ControlPaint method DrawButton in order to draw the button of the form
ControlPaint.DrawButton(g, ((Button)c).Left, ((Button)c).Top, ((Button)c).Width,((Button)c).Height, ButtonState.Normal);
// We also need to draw the text
g.DrawString(b.Text, b.Font, new SolidBrush(b.ForeColor), b.Left + b.Width/2 - g.MeasureString(b.Text,
b.Font).Width/2, b.Top + b.Height/2 - g.MeasureString("a", b.Font).Height/2,
new StringFormat());
break;
case "TextBox":TextBox t = (TextBox)c;
// Draw a text box by drawing a pushed in button and filling the rectangle with the background color and the text
// of the TextBox control
// First the sunken border
ControlPaint.DrawButton(g, t.Left, t.Top, t.Width, t.Height, ButtonState.Pushed );
// Then fill it with the background of the textbox
g.FillRectangle(new SolidBrush(t.BackColor), t.Left+1, t.Top + 1, t.Width+2,t.Height -2);
// Finally draw the string inside
g.DrawString(t.Text, t.Font, new SolidBrush(t.ForeColor), t.Left + 2,t.Top + t.Height/2 - g.MeasureString("a", t.Font).Height/2, new StringFormat());
break;
case "CheckBox":// We have a checkbox to paint, unbox it
CheckBox cb = (CheckBox)c;
// Use the DrawCheckBox command to draw a checkbox and pass the button state to paint it checked or unchecked
if (cb.Checked)
ControlPaint.DrawCheckBox(g, cb.Left, cb.Top, cb.Height/2, cb.Height/2,ButtonState.Checked);
else
ControlPaint.DrawCheckBox(g, cb.Left, cb.Top, cb.Height/2, cb.Height/2,ButtonState.Normal);
// Don't forget the checkbox text
g.DrawString(cb.Text, cb.Font, new SolidBrush(cb.ForeColor), cb.Right -cb.Height -g.MeasureString(cb.Text, cb.Font).Width, cb.Top, new StringFormat());
break;
}
}
}

The code above cycles through each control in the form and paints the control to the Graphics object.  The code takes advantage of the ControlPaint methods we mentioned above.  The DrawButton method is used to paint both the 3D button controls and the 3D text boxes.  The DrawCheckBox method of the ControlPaint class is used to draw the 3D checkbox.  In every case we need to draw the text separately from the control using the DrawString method of the Graphics Object.  We also needed to fill in the TextBox background with the FillRectangle method in the Graphics object.

Conclusion

Much more code can be added to this project to handle radio buttons, listviews, listboxes, and comboboxes.  The ControlPaint class contains  methods that can help you to paint other Window Form controls such as DrawScrollButton, DrawRadioButton, DrawGrid, DrawComboButton and DrawFocusRectangle.  If your form only contains edit boxes, checkboxes, and buttons, then this code may cover the bulk of your work.


Login to add your contents and source code to this article
 About the author
 
Mike Gold
Michael Gold is President of Microgold Software Inc., makers of the WithClass UML Tool. His company is a Microsoft VBA Partner and Borland Partner. Mike is a Microsoft MVP and founding member of C# Corner. He has a BSEE and MEng EE from Cornell University and has consulted for Chase Manhattan Bank, JP Morgan, Merrill Lynch, and Charles Schwab. Currently he is a senior developer at Finisar Corp. He has been involved in several .NET book projects, and is currently working on a book for using .NET with embedded systems. He can be reached at mike@c-sharpcorner.com
Looking for C# Consulting?
C# Consulting is founded in 2002 by the founders of C# Corner. Unlike a traditional consulting company, our consultants are well-known experts in .NET and many of them are MVPs, authors, and trainers. We specialize in Microsoft .NET development and utilize Agile Development and Extreme Programming practices to provide fast pace quick turnaround results. Our software development model is a mix of Agile Development, traditional SDLC, and Waterfall models.
Click here to learn more about C# Consulting.
 
Introducing MaxV - one click. infinite control. Hyper-V Hosting from MaximumASP.
Finally – a virtual platform that delivers next-generation Windows Server 2008 Hyper-V virtualization technology from a managed hosting partner you can truly depend on. Visit www.maximumasp.com/max for a FREE 30 day trial. Hurry offer ends soon. Climb aboard the MaxV platform and take advantage of High Availability, Intelligent Monitoring, Recurrent Backups, and Scalability – with no hassle or hidden fees. As a managed hosting partner focused solely on Microsoft technologies since 2000, MaximumASP is uniquely qualified to provide the superior support that our business is built on. Unparalleled expertise with Microsoft technologies lead to working directly with Microsoft as first to offer IIS 7 and SQL 2008 betas in a hosted environment; partnering in the Go Live Program for Hyper-V; and product co-launches built on WS 2008 with Hyper-V technology.
Dynamic PDF
ceTE software specializes in components for dynamic PDF generation and manipulation. The DynamicPDF™ product line allows you to dynamically generate PDF documents, merge PDF documents and new content to existing PDF documents from within your applications.
SQL and .NET performance profiling in one place
Investigate SQL and .NET code side-by-side with ANTS Performance Profiler 6, so you can see which is causing the problem without switching tools.
Go.NET
Build custom interactive diagrams, network, workflow editors, flowcharts, or software design tools. Includes many predefined kinds of nodes, links, and basic shapes. Supports layers, scrolling, zooming, selection, drag-and-drop, clipboard, in-place editing, tooltips, grids, printing, overview window, palette. 100% implemented in C# as a managed .NET Control. Document/View/Tool architecture with many properties&events. Optional automatic layout.
Dundas Software
Dundas Chart for .NET is the most advanced .NET charting package available today.  With an extremely complete feature set, elegant architecture and easy implementation, Dundas Chart can quickly add advanced Charting functionality to enhance and transform ASP.NET and Windows Forms applications.  Whether you are implementing charting into internal projects, or building applications for clients, Dundas Chart offers advanced technology and advanced results to get the most out of data.
60 FREE UI Controls from DevExpress
Register for your FREE copy on over 60 free presentation controls from DevExpress - Absolutely Free-of-Charge without any royalties or distribution costs. Visit Devexpress.com/60 today. Free controls include advanced lists box, dropdown calendar, rich text edit, spin edit, tab control and so much more!

DevExpress engineers feature rich presentation controls and reporting tools for WinForms, ASP.NET, WPF, and Silverlight. Our technologies help you build your best, see complex software with greater clarity and deliver compelling business solutions for Windows and the web in the shortest possible time.
Clickatell's SMS Gateway
Clickatell's Developer Solutions allow you to SMS enable any website or application via a range of API's. Learn More about our API connections.
Free access to .NET Memory Management video
Everything you need to know about Garbage Collection, Temporary Objects, Fragmentation, Finalization and common causes of memory leaks in .NET. Watch the video here.
Microsoft Visual Studio 2010
Visualize your workspace with new multiple monitor support, powerful Web development, new SharePoint support with tons of templates and Web parts, and more accurate targeting of any version of the .NET Framework. Get set to unleash your creativity.
Nevron Chart for .NET 2010.1 Now Available
The leading .NET charting control now features PDF, Flash and Silverlight export, visualization of large datasets and more. Deliver true charting functionality to your BI, Scorecard, Presentation or Scientific apps. Download evaluation now.
Developer-Ready ASP.NET 2.0 Web Hosting with 3 MONTHS FREE
Now supporting .NET 3.0 Framework with Windows Workflow Foundation, Windows Communication Foundation (WCF), Windows Presentation Foundation (WPF), windows CardSpace (WCS)! Providing more flexibility for Developers with Web Services Support and a User/Permission Manger. Also supporting MS SQL 2005/2000 with Real-Time Backups, FREE Automated Attach .MDF Tool, FREE SQL Restore and Shrink SQL DB Tools, and SQL
Read the Top 10 Books for Microsoft Developers, 15 Days FREE
Read the Top 10 Books for Microsoft Developers, 15 Days FREE
Try Safari Books Online - 15 Days FREE + 15% Off for 1 Year
Try Safari Books Online - 15 Days FREE + 15% Off for 1 Year
 
 Post a Feedback, Comment, or Question about this article
Subject:
Comment:
Become a Sponsor
 Comments
help for printing data in a random or seq file by ahmad On February 15, 2007
I wrote some class for my data and store them in some random or seq files . I see some controls in microsoft visual stdio 2005 for printing like ( PrintDocument) but I dont know how to use them. I need for your help very much. thanks
Reply | Email | Delete | Modify | 
Extra bits of info by Nigel On April 26, 2007
Please supply info on resX, resY and the value of ScreenResolution.
Reply | Email | Delete | Modify | 
Re: Extra bits of info by mohammad On January 17, 2010
Hi Nigel, i am just wondering if you got any reply on the Screen Resolution thing
on this page

http://www.c-sharpcorner.com/UploadFile/mgold/HowToPrintingFormControlsinCSharpand.NET11212005063649AM/HowToPrintingFormControlsinCSharpand.NET.aspx
Reply | Email | Delete | Modify | 
ControlPaint by Damon On January 22, 2008

How would you print things like textboxes out if they were inside a label?

Reply | Email | Delete | Modify | 
how to print radiobutton and datagridview by this method by Nishant On May 20, 2009

Thank you for this code.

i have a doubt, how to print datagridview and radiobutton by this method.

pls help me out
Reply | Email | Delete | Modify | 
Thanks by Dario On August 5, 2010
Muchas Gracias por tu codigo
me sera de mucha ayuda
Reply | Email | Delete | Modify | 
Update available ? by Steffan On August 17, 2010
Any chance this can be updated to also accomodate User Controls and GroupBoxes (which in turn contain controls) ?
Reply | Email | Delete | Modify | 

 Hosted by MaximumASP  |  Found a broken link?  |  Contact Us  |  Terms & conditions  |  Privacy Policy  |  Site Map  |  Suggest an Idea  |  Media Kit
Current Version: 5.2010.8.14
 © 2010  contents copyright of their authors. Rest everything copyright Mindcracker. All rights reserved.