Basic printing

ddanbe 2 Tallied Votes 359 Views Share

These are (I guess) the most basic printing instructions in C#, to let some printed paper coming out of a printer.
Start a new Forms application, drop a ComboBox, a Label and a Button on the form. Implement a form Load and a Button Click event and fill in the rest of the above code. I hope the comments in it are sufficient to understand the code. Feel free to ask,if not. If you find any errors in it, or if you have any remarks, please inform me as well.

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Drawing.Printing; //** include this

namespace BasicPrinting
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            // get the name of the default printer
            PrinterSettings settings = new PrinterSettings();
            label1.Text = settings.PrinterName;

            // alternatively choose from a combo with the static property InstalledPrinters
            foreach (string printer in PrinterSettings.InstalledPrinters)
            {
                comboBox1.Items.Add(printer);
            }
            comboBox1.Text = comboBox1.Items[0].ToString();

            //The class PrintDocument also has a PrinterSettings property 
        }

        private void button1_Click(object sender, EventArgs e)
        {
            //Create a PrintDocument object
            PrintDocument PrintDoc = new PrintDocument();
            //Set PrinterName as the selected printer in the printers list, or in this case use label1.Text
            PrintDoc.PrinterSettings.PrinterName = comboBox1.SelectedItem.ToString();
            //Add PrintPage event handler
            PrintDoc.PrintPage += new PrintPageEventHandler(printAPage);
            //Print the document, also fires the PrintPage eventhandler
            PrintDoc.Print();
        }

        private void printAPage(object sender, PrintPageEventArgs PE)
        {
            const int Xpos = 50;
            const int Ypos = 100;

            //It is handy to make the name of the Graphics object smaller
            Graphics G = PE.Graphics;
            //Create a font arial with size 16
            Font font = new Font("Arial", 16);
            //Create a solid brush with blue color
            SolidBrush brush = new SolidBrush(Color.Blue);
            // Create a rectangle
            Rectangle rect = new Rectangle(Xpos, Ypos, 250, 50);
            //Draw text
            G.DrawString("Printing: Hello, World! ", font, brush, rect);
            //Put a red Rectangle around the text
            Pen pen = new Pen(Color.Red);
            G.DrawRectangle(pen, Xpos, Ypos, 250, 50);
            //etc.
        }
    }
}