How to Print Text in a Windows Form Application Using C#
By FoxLearn 12/2/2024 2:35:00 PM 13.11K
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 use Advanced Filter DataGridView in C#
- How to Print DataGridView with Header & Footer with Landscape in C#
- How to Add Combobox to DataGridView in C#
- How to Get all Forms and Open Form with Form Name in C#
- How to Hide a WinForm in C#
- How to zoom an image in C#
- How to Open and Show a PDF file in C#
- How to Use Form Load and Button click Event in C#