Csharp/CSharp Tutorial/GUI Windows Forms/Print Preview Dialog

Материал из .Net Framework эксперт
Перейти к: навигация, поиск

Output the PrinterSettings information

using System;
using System.Drawing;
using System.Collections;
using System.ruponentModel;
using System.Windows.Forms;
using System.Data;
using System.Drawing.Printing;
public class frmMain : System.Windows.Forms.Form {
    public frmMain() {
        this.Paint += new System.Windows.Forms.PaintEventHandler(this.frmMain_Paint);
    }
    [STAThread]
    static void Main() {
        Application.Run(new frmMain());
    }
    private void frmMain_Paint(object sender, System.Windows.Forms.PaintEventArgs e) {
        PrinterSettings pSettings = new PrinterSettings();
        Font printFont = new Font("Arial", 10);
        int nTextPosY = 0;
        int nTextPosX = 5;
        int nHeight = (int)printFont.GetHeight(e.Graphics);
        foreach (string sPtr in PrinterSettings.InstalledPrinters) {
            pSettings.PrinterName = "BadName";
            e.Graphics.DrawString(sPtr, printFont, Brushes.Black, nTextPosX, nTextPosY + 5);
            e.Graphics.DrawString("Can Duplex: " + pSettings.CanDuplex.ToString(),
                printFont, Brushes.Black, nTextPosX + 10, nTextPosY + (5 + nHeight));
            e.Graphics.DrawString("Is Default: " + pSettings.IsDefaultPrinter.ToString(),
                printFont, Brushes.Black, nTextPosX + 10, nTextPosY + (5 + nHeight * 2));
            e.Graphics.DrawString("Is Plotter: " + pSettings.IsPlotter.ToString(),
                printFont, Brushes.Black, nTextPosX + 10, nTextPosY + (5 + nHeight * 3));
            e.Graphics.DrawString("Landscape Angle: " + pSettings.LandscapeAngle.ToString(),
                printFont, Brushes.Black, nTextPosX + 10, nTextPosY + (5 + nHeight * 4));
            e.Graphics.DrawString("Maximum Copies: " + pSettings.MaximumCopies.ToString(),
                printFont, Brushes.Black, nTextPosX + 10, nTextPosY + (5 + nHeight * 5));
            e.Graphics.DrawString("Maximum Page: " + pSettings.MaximumPage.ToString(),
                printFont, Brushes.Black, nTextPosX + 10, nTextPosY + (5 + nHeight * 6));
            e.Graphics.DrawString("Minimum Page: " + pSettings.MinimumPage.ToString(),
                printFont, Brushes.Black, nTextPosX + 10, nTextPosY + (5 + nHeight * 7));
            e.Graphics.DrawString("Supports Color: " + pSettings.SupportsColor.ToString(),
                printFont, Brushes.Black, nTextPosX + 10, nTextPosY + (5 + nHeight * 8));
            nTextPosY = nTextPosY + ((5 + nHeight * 8) + nHeight);
        }
        return;
    }
}

Print Preview Dialog for printing text file

using System;
using System.Drawing;
using System.Collections;
using System.ruponentModel;
using System.Windows.Forms;
using System.Data;
using System.IO;
using System.Drawing.Printing;
public class PrintPreviewDialog : System.Windows.Forms.Form
{
  private System.Windows.Forms.TextBox txtFile;
  private System.Windows.Forms.Button btnOpenFile;
  private System.Windows.Forms.Button btnSaveFile;
  private System.ruponentModel.Container components = null;
  private System.Windows.Forms.Button btnPageSetup;
  private System.Windows.Forms.Button btnPrint;
  private System.Windows.Forms.Button btnPrintPreview;  
  
  private String strFileName;
  private Font currentFont= Font;
  private PrintDocument printDocument = new PrintDocument();
  private StringReader stringReader;
  private OpenFileDialog openFileDialog = new OpenFileDialog();
  public PrintPreviewDialog()
  {
    InitializeComponent();
    
    printDocument.PrintPage += new PrintPageEventHandler(pdPrintPage);
    printDocument.BeginPrint += new PrintEventHandler(pdBeginPrint);
    printDocument.EndPrint += new PrintEventHandler(pdEndPrint);
  }
  private void InitializeComponent()
  {
    this.txtFile = new System.Windows.Forms.TextBox();
    this.btnOpenFile = new System.Windows.Forms.Button();
    this.btnSaveFile = new System.Windows.Forms.Button();
    this.btnPageSetup = new System.Windows.Forms.Button();
    this.btnPrint = new System.Windows.Forms.Button();
    this.btnPrintPreview = new System.Windows.Forms.Button();
    this.SuspendLayout();
    // 
    // txtFile
    // 
    this.txtFile.Anchor = (((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom) 
      | System.Windows.Forms.AnchorStyles.Left) 
      | System.Windows.Forms.AnchorStyles.Right);
    this.txtFile.Location = new System.Drawing.Point(40, 24);
    this.txtFile.Multiline = true;
    this.txtFile.Name = "txtFile";
    this.txtFile.Size = new System.Drawing.Size(500, 150);
    this.txtFile.TabIndex = 0;
    this.txtFile.Text = "";
    // 
    // btnOpenFile
    // 
    this.btnOpenFile.Anchor = (System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left);
    this.btnOpenFile.Location = new System.Drawing.Point(48, 256);
    this.btnOpenFile.Name = "btnOpenFile";
    this.btnOpenFile.TabIndex = 1;
    this.btnOpenFile.Text = "Open File";
    this.btnOpenFile.Click += new System.EventHandler(this.btnOpenFile_Click);
    // 
    // btnSaveFile
    // 
    this.btnSaveFile.Anchor = (System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left);
    this.btnSaveFile.Location = new System.Drawing.Point(144, 256);
    this.btnSaveFile.Name = "btnSaveFile";
    this.btnSaveFile.TabIndex = 2;
    this.btnSaveFile.Text = "Save File";
    this.btnSaveFile.Click += new System.EventHandler(this.btnSaveFile_Click);
    // 
    // btnPageSetup
    // 
    this.btnPageSetup.Anchor = (System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left);
    this.btnPageSetup.Location = new System.Drawing.Point(240, 344);
    this.btnPageSetup.Name = "btnPageSetup";
    this.btnPageSetup.TabIndex = 8;
    this.btnPageSetup.Text = "Page Setup";
    this.btnPageSetup.Click += new System.EventHandler(this.btnPageSetup_Click);
    // 
    // btnPrint
    // 
    this.btnPrint.Anchor = (System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left);
    this.btnPrint.Location = new System.Drawing.Point(48, 344);
    this.btnPrint.Name = "btnPrint";
    this.btnPrint.TabIndex = 6;
    this.btnPrint.Text = "Print";
    this.btnPrint.Click += new System.EventHandler(this.btnPrint_Click);
    // 
    // btnPrintPreview
    // 
    this.btnPrintPreview.Anchor = (System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left);
    this.btnPrintPreview.Location = new System.Drawing.Point(144, 344);
    this.btnPrintPreview.Name = "btnPrintPreview";
    this.btnPrintPreview.Size = new System.Drawing.Size(80, 23);
    this.btnPrintPreview.TabIndex = 7;
    this.btnPrintPreview.Text = "Print Preview";
    this.btnPrintPreview.Click += new System.EventHandler(this.btnPrintPreview_Click);
    // 
    // PrintPreviewDialog
    // 
    this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);
    this.ClientSize = new System.Drawing.Size(592, 398);
    this.Controls.AddRange(new System.Windows.Forms.Control[] {
                                             this.btnPrintPreview,
                                             this.btnPrint,
                                             this.btnPageSetup,
                                             this.btnSaveFile,
                                             this.btnOpenFile,
                                             this.txtFile});
    this.ResumeLayout(false);
  }
  [STAThread]
  static void Main() 
  {
    Application.Run(new PrintPreviewDialog());
  }
  private void btnOpenFile_Click(object sender, System.EventArgs e)
  {
    openFileDialog.InitialDirectory = @"c:\";
    openFileDialog.Filter = "Text files (*.txt)|*.txt|" +
            "All files (*.*)|*.*";
    openFileDialog.FilterIndex = 1;              //  1 based index
    
    if (openFileDialog.ShowDialog() == DialogResult.OK)
    {
      StreamReader reader = new StreamReader(openFileDialog.FileName);
      try
      {
        strFileName = openFileDialog.FileName;
        txtFile.Text = reader.ReadToEnd();
      }
      catch (Exception ex)
      {
        MessageBox.Show(ex.Message);
        return;
      }
      finally
      {
        reader.Close();
      }
    }
  }
  private void btnSaveFile_Click(object sender, System.EventArgs e)
  {
    SaveFileDialog sfd = new SaveFileDialog();
    sfd.InitialDirectory = @"c:\";
    sfd.Filter = "Text files (*.txt)|*.txt|" +
            "All files (*.*)|*.*";
    sfd.FilterIndex = 1;              //  1 based index
    if (strFileName != null)
      sfd.FileName = strFileName;
    else
      sfd.FileName = "*.txt";
    
    if (sfd.ShowDialog() == DialogResult.OK)
    {
      StreamWriter writer = new StreamWriter(strFileName,false);
      try
      {
        strFileName = sfd.FileName;
        writer.Write(txtFile.Text);
      }
      catch(Exception ex)
      {
        MessageBox.Show(ex.Message);
        return;
      }
      finally
      {
        writer.Close();
      }
    }
  }
  private void btnPageSetup_Click(object sender, System.EventArgs e)
  {
    PageSetupDialog psd = new PageSetupDialog();
    psd.Document = printDocument;
    psd.ShowDialog();
  }
  private void btnPrint_Click(object sender, System.EventArgs e)
  {
    PrintDialog pdlg = new PrintDialog();
    pdlg.Document = printDocument;
    
    if (pdlg.ShowDialog() == DialogResult.OK)
    {
      try
      {
        printDocument.Print();
      }
      catch(Exception ex)
      {
        MessageBox.Show("Print error: " + ex.Message);
      }
    }
  }
  private void btnPrintPreview_Click(object sender, System.EventArgs e)
  {
    PrintPreviewDialog ppdlg = new PrintPreviewDialog();
    ppdlg.Document = printDocument;
    ppdlg.ShowDialog();
  }
  private void pdPrintPage(object sender, PrintPageEventArgs e)
  {
    float linesPerPage = 0;
    float verticalOffset = 0;
    float leftMargin = e.MarginBounds.Left;
    float topMargin = e.MarginBounds.Top;
    int linesPrinted = 0;
    String strLine = null;
    linesPerPage = e.MarginBounds.Height / currentFont.GetHeight(e.Graphics);
    
    while (linesPrinted < linesPerPage &&
        ((strLine = stringReader.ReadLine())!= null ))
    {
      verticalOffset = topMargin + (linesPrinted * currentFont.GetHeight(e.Graphics));
      e.Graphics.DrawString(strLine, currentFont, Brushes.Black, leftMargin, verticalOffset);
      linesPrinted++;
    }
    
    if (strLine != null)
      e.HasMorePages = true;
    else
      e.HasMorePages = false;
      
  }
  private void pdBeginPrint(object sender, PrintEventArgs e)
  {
    stringReader = new StringReader(txtFile.Text);
    currentFont = txtFile.Font;
  }
  private void pdEndPrint(object sender, PrintEventArgs e)
  {
    stringReader.Close();
    MessageBox.Show("Done printing.");
  }
}

Show PrintPreview Dialog before print out a document

using System;        
using System.Drawing;
using System.Collections;
using System.ruponentModel;
using System.Windows.Forms;
using System.Data;
namespace PrintExample
{
  /// <summary>
  /// Summary description for PrintPreviewDialog.
  /// </summary>
  public class PrintPreviewDialog : System.Windows.Forms.Form
  {
    private System.Windows.Forms.MainMenu mainMenu1;
    private System.Windows.Forms.MenuItem menuItem1;
    private System.Drawing.Printing.PrintDocument printDocument1;
    private System.Windows.Forms.PrintPreviewDialog printPreviewDialog1;
    private System.Windows.Forms.PrintDialog printDialog1;
    private System.Windows.Forms.MenuItem menuItem2;
    private System.Windows.Forms.MenuItem menuItem3;
    private System.Windows.Forms.PageSetupDialog pageSetupDialog1;
    private System.Windows.Forms.MenuItem menuItem4;
    /// <summary>
    /// Required designer variable.
    /// </summary>
    private System.ruponentModel.Container components = null;
    public PrintPreviewDialog()
    {
      //
      // Required for Windows Form Designer support
      //
      InitializeComponent();
      //
      // TODO: Add any constructor code after InitializeComponent call
      //
    }
    /// <summary>
    /// Clean up any resources being used.
    /// </summary>
    protected override void Dispose( bool disposing )
    {
      if( disposing )
      {
        if (components != null) 
        {
          components.Dispose();
        }
      }
      base.Dispose( disposing );
    }
    #region Windows Form Designer generated code
    /// <summary>
    /// Required method for Designer support - do not modify
    /// the contents of this method with the code editor.
    /// </summary>
    private void InitializeComponent()
    {
      this.mainMenu1 = new System.Windows.Forms.MainMenu();
      this.menuItem1 = new System.Windows.Forms.MenuItem();
      this.menuItem2 = new System.Windows.Forms.MenuItem();
      this.menuItem3 = new System.Windows.Forms.MenuItem();
      this.printDocument1 = new System.Drawing.Printing.PrintDocument();
      this.printPreviewDialog1 = new System.Windows.Forms.PrintPreviewDialog();
      this.printDialog1 = new System.Windows.Forms.PrintDialog();
      this.pageSetupDialog1 = new System.Windows.Forms.PageSetupDialog();
      this.menuItem4 = new System.Windows.Forms.MenuItem();
      // 
      // mainMenu1
      // 
      this.mainMenu1.MenuItems.AddRange(new System.Windows.Forms.MenuItem[] {
                                            this.menuItem1});
      // 
      // menuItem1
      // 
      this.menuItem1.Index = 0;
      this.menuItem1.MenuItems.AddRange(new System.Windows.Forms.MenuItem[] {
                                            this.menuItem4,
                                            this.menuItem2,
                                            this.menuItem3});
      this.menuItem1.Text = "File";
      // 
      // menuItem2
      // 
      this.menuItem2.Index = 1;
      this.menuItem2.Text = "Print";
      this.menuItem2.Click += new System.EventHandler(this.menuItem2_Click);
      // 
      // menuItem3
      // 
      this.menuItem3.Index = 2;
      this.menuItem3.Text = "Print preview";
      this.menuItem3.Click += new System.EventHandler(this.menuItem3_Click);
      // 
      // printDocument1
      // 
      this.printDocument1.PrintPage += new System.Drawing.Printing.PrintPageEventHandler(this.printDocument1_PrintPage);
      // 
      // printPreviewDialog1
      // 
      this.printPreviewDialog1.AutoScrollMargin = new System.Drawing.Size(0, 0);
      this.printPreviewDialog1.AutoScrollMinSize = new System.Drawing.Size(0, 0);
      this.printPreviewDialog1.ClientSize = new System.Drawing.Size(400, 300);
      this.printPreviewDialog1.Document = this.printDocument1;
      this.printPreviewDialog1.Enabled = true;
      this.printPreviewDialog1.Location = new System.Drawing.Point(272, 13);
      this.printPreviewDialog1.MaximumSize = new System.Drawing.Size(0, 0);
      this.printPreviewDialog1.Name = "printPreviewDialog1";
      this.printPreviewDialog1.Opacity = 1;
      this.printPreviewDialog1.TransparencyKey = System.Drawing.Color.Empty;
      this.printPreviewDialog1.Visible = false;
      // 
      // printDialog1
      // 
      this.printDialog1.Document = this.printDocument1;
      // 
      // pageSetupDialog1
      // 
      this.pageSetupDialog1.Document = this.printDocument1;
      // 
      // menuItem4
      // 
      this.menuItem4.Index = 0;
      this.menuItem4.Text = "Page setup";
      this.menuItem4.Click += new System.EventHandler(this.menuItem4_Click);
      // 
      // PrintPreviewDialog
      // 
      this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);
      this.ClientSize = new System.Drawing.Size(292, 266);
      this.Menu = this.mainMenu1;
      this.Name = "PrintPreviewDialog";
      this.Text = "Print Example";
    }
    #endregion
    /// <summary>
    /// The main entry point for the application.
    /// </summary>
    [STAThread]
    static void Main() 
    {
      Application.Run(new PrintPreviewDialog());
    }
    private int currentPage;
    private void menuItem2_Click(object sender, System.EventArgs e)
    {
      if ( printDialog1.ShowDialog( this ) == DialogResult.OK )
      {
        currentPage = 1;
        printDocument1.Print();
      }
    }
    private void menuItem3_Click(object sender, System.EventArgs e)
    {
      currentPage = 1;
      printPreviewDialog1.ShowDialog( this );
    }
    private void printDocument1_PrintPage(object sender, System.Drawing.Printing.PrintPageEventArgs e)
    {
      e.Graphics.DrawString( "Page " + currentPage, new Font( "Times New Roman", 15 ), 
        Brushes.Black, e.MarginBounds.Left, e.MarginBounds.Top );
      currentPage++;
      if ( currentPage > 3 )
      {
        e.HasMorePages = false;
      }
      else
      {
        e.HasMorePages = true;
      }
    }
    private void menuItem4_Click(object sender, System.EventArgs e)
    {
      pageSetupDialog1.ShowDialog( this );
    }
  }
}