If you have a simple
need to only print the Form (window) you are currently viewing in .NET you can
use the PrintForm tool.
The PrintForm component
is described at http://msdn.microsoft.com/en-us/library/bb690938.aspx
[1] with the following.
The PrintForm component enables you
to print an image of a form to a printer, to a print preview window, or to a
file without using a PrintDocument component.
With that description let's get started.
Create a Program
I am using Visual Studio Professional 2012.
Start Visual Studio Pro and click New Project.
- Enter the program Name "PrintForm-Test
- Click OK
Add a few Controls to you form.
I am adding
·
PictureBox
·
Panel
·
Label
·
RichTextBox
·
Button
Here is a view of what I made.
Drag and drop a PrintForm component on the Windows form.
Double click on Print to create and open the click event.
Add the following piece of code.
private void button1_Click(object sender, EventArgs e) {
printForm1.Print();
}
|
Just adding the printForm1.Print() will cause this Window to
be printed.
Click Start to compile and run the program.
I copied some text with different font styles and colors
from Word an pasted it in the RichTextBox.
Click Print (this
will automatically print this window to your default printer)
This is my print results.
You can add a print preview by adding the following code.
private void button1_Click(object sender, EventArgs e) {
printForm1.PrintAction =
System.Drawing.Printing.PrintAction.PrintToPreview;
printForm1.Print();
}
|
This will open the default printPreview tool when you hit
print.
Running the program again and clicking print you will get
this…
From here you can preview and print.
Button vs Menu
The PrintForm will print the entire Form, in this case, the
Print Button is included in this.
One simple way to fix this is to add a MenuStrip and have a
Print selection from there.
Remove the Print Button and add a MenuStrip and add a Print
option to it.
Double Click on the Print Option to create/Open its event.
Put in the same code.
private void printToolStripMenuItem_Click(object sender,
EventArgs e) {
printForm1.PrintAction =
System.Drawing.Printing.PrintAction.PrintToPreview;
printForm1.Print();
}
|
Run the Program and now click on the Print menu item.
You will see that the Print Preview does not show the Menu
items. This is the default behavior for
PrintForm.
Here is the printout.
It does not print the menu.
Conclusions
PrintForm is a good simple print tool to use to print the
contents of a Window. It does not give
you fine grain control but it may be all you need in a great many situations.
References
[1] PrintForm Component (Visual Basic)
Visited 8/2013
No comments:
Post a Comment