How to Print Text in a Windows Form Application Using C#
By FoxLearn 12/2/2024 2:35:00 PM 12.88K
Printing is an essential feature in many applications, and Windows Forms provides a simple way to achieve this using the PrintDocument
and PrintPreviewDialog
components. This article demonstrates how to print text in a Windows Forms application.
How to Print Text in a Windows Form Application Using C#?
Open Visual Studio, then click New Project, then select Visual C# on the left, then Windows and then select Windows Forms Application. Name your project "PrintText" and then click OK
Drag and drop the Label, TextBox and Button from the Visual Toolbox onto your form designer, then design your form as shown below.
You need to add a PrintDocument, PrintPreviewDialog to your form.
Set the PrintPage
event of printDocument1
to printDocument1_PrintPage
.
private void printDocument1_PrintPage(object sender, System.Drawing.Printing.PrintPageEventArgs e) { // Draw text to your document e.Graphics.DrawString(txtValue.Text, new Font("Times New Roman", 14, FontStyle.Bold), Brushes.Black, new PointF(100, 100)); }
This method determines the content that will appear on the printed page. The e.Graphics.DrawString
method is used to draw the text.
Assign the Click
event of the print button (btnPrint
) to Print_Click
.
private void Print_Click(object sender, EventArgs e) { // Open print preview dialog if (printPreviewDialog1.ShowDialog() == DialogResult.OK) printDocument1.Print(); }
This method displays a print preview dialog and sends the document to the printer if confirmed.
Enter text in the txtValue
TextBox, then click the "Print" button to open the preview dialog. Confirm the dialog to print the text.
VIDEO TUTORIAL
- How to fill ComboBox and DataGridView automatically in C#
- How to Read text file and Sort list in C#
- How to pass ListView row data into another Form in C#
- How to read and write to text file in C#
- How to make a Countdown Timer in C#
- How to Display selected Row from DataGridView to TextBox in C#
- How to Get all Forms and Open Form with Form Name in C#
- How to Get Checked Items In a CheckedListBox in C#