Printing a document in C#
I am trying to print a document with .txt extension and for that I am referring to my course book but confused. Here is the source code given in the book :
private void Print_Click(object sender, EventArgs e)
{
printDialog1.Document = printDocument1 // there is no object in my progr开发者_开发问答am names ad printDocument1
DialogResult result = printDialog1.ShowDialog();
if (result == DialogResult.OK)
{
printDocument1.Print();
and there is lot more code given
Your example is assuming that a PrintDocument object has been dragged onto the form from the toolbox: you could though just as easily create the object yourself.
private void Print_Click(object sender, EventArgs e)
{
PrintDocument printDocument = new PrintDocument();
printDocument.PrintPage += new PrintPageEventHandler(printDocument_PrintPage);
PrintDialog printDialog = new PrintDialog
{
Document = printDocument
};
DialogResult result = printDialog.ShowDialog();
if (result == DialogResult.OK)
{
printDocument.Print(); // Raises PrintPage event
}
}
void printDocument_PrintPage(object sender, PrintPageEventArgs e)
{
e.Graphics.DrawString(...);
}
Open the form in design mode. Locate the PrintDocument control in the toolbox. Drag and drop it onto your form. That adds a field to your form class named "printDocument1". Next, double-click the printDocument1 image displayed below the form. That adds the PrintPage event handler. Use the code from your book.
Review the instructions in the book, it should have mentioned this. Best to use its step-by-step instructions rather than mine.
If you want to print an existing .txt file, you can have Windows print it:
using System.Diagnostics;
Process myProcess = new Process();
myProcess.StartInfo.FileName = "C:\\thefile.txt"; // adjust to your needs
myProcess.StartInfo.Verb = "print";
myProcess.Start();
See Process.
精彩评论