Search Forum
(53671 Postings)
Search Site/Articles

Archived Articles
712 Articles

C# Books
C# Consultants
What Is C#?
Download Compiler
Code Archive
Archived Articles
Advertise
Contribute
C# Jobs
Beginners Tutorial
C# Contractors
C# Consulting
Links
C# Manual
Contact Us
Legal

GoDiagram for .NET from Northwoods Software www.nwoods.com


 
Printable Version

Dialog Objects in .NET
By Vijay Patil & Emil Tsankov


.NET environment has provided us with various classes to use the Dialog objects. This paper explains how to create and use the following dialog boxes in .NET environment:

  1. OpenFileDialog
  2. FontDialog
  3. ColorDialog
  4. PrintPreviewDialog
  5. PrintDialog
  6. SaveFileDialog

Object hierarchy of the above dialog objects is given as
Object
   MarshalByRefObject
      Component
         CommonDialog
            ColorDialog
            FileDialog
               OpenFileDialog
               SaveFileDialog
            FontDialog
            PrintDialog
            
In this example we have created an application that opens a dialog box to open a txt tile using a OpenFileDialog button. On click of FontDialog button, Font Dialog box is opened. The user can select Font name, style, size etc. ColorDialog button helps the user select a particular color to be used for the font. PrintPreview button helps the user preview the formatted document. PrintDialog button helps the user print the document. With the help of SaveDialog button, the user can open ‘Save As’ dialog box to save the copy of the file as a new file. All the selected parameters are displayed with the help of a label. A runtime view of the FORM created is give below.

DialogObjects200.jpg


1. OpenFileDialog


On click of the first button, an object of OpenFileDialog class is defined and initialized. The following properties of the object (inherited from FileDialog) have been used.

InitialDirectory
Gets or sets the initial directory displayed by the file dialog box.
Filter
Gets or sets the current file name filter string, which determines the choices that appear in the “Save as file type” or “Files of type” box in the dialog box.
FilterIndex
Gets or sets the index of the filter currently selected in the file dialog box.
RestoreDirectory
Gets or sets a value indicating whether the dialog box restores the current directory before closing.
FileName
Gets or sets a string containing the file name selected in the file dialog box.

The dialog box looks like this:


This is default directory
Filter applied to this field
File to be opened
DialogObjects201.jpg

private void btnOpenFileDialog_Click(object sender, System.EventArgs e)
{
OpenFileDialog openFileDialog1 = new OpenFileDialog();
openFileDialog1.InitialDirectory = "c:\" ;
openFileDialog1.Filter = "txt files (*.txt)|*.txt|All files (*.*)|*.*" ;
openFileDialog1.FilterIndex = 2 ;
openFileDialog1.RestoreDirectory = true ;
if(openFileDialog1.ShowDialog() == DialogResult.OK)
{
fName = openFileDialog1.FileName;
showInfo();
sr = new StreamReader(fName);
}
}

Other Public Instance Properties (inherited from FileDialog) are listed below

AddExtension
Gets or sets a value indicating whether the dialog box automatically adds an extension to a file name if the user omits the extension.
CheckPathExists
Gets or sets a value indicating whether the dialog box displays a warning if the user specifies a path that does not exist.
DefaultExt
Gets or sets the default file extension.
DereferenceLinks
Gets or sets a value indicating whether the dialog box returns the location of the file referenced by the shortcut or whether it returns the location of the shortcut
FileNames
Gets the file names of all selected files in the dialog box.
ShowHelp
Gets or sets a value indicating whether the Help button is displayed in the file dialog.
Title
Gets or sets the file dialog box title.
ValidateNames
Gets or sets a value indicating whether the dialog box accepts only valid Win32 file names.

Public Instance Methods


ShowDialog
Runs a common dialog box. Only this method has been used in our example.
Dispose
Overloaded. Releases the resources used by the Component
Equals
Overloaded. Determines whether two Object instances are equal.
GetHashCode
Serves as a hash function for a particular type, suitable for use in hashing algorithms and data structures like a hash table.
GetLifetimeService
Retrieves a lifetime service object that controls the lifetime policy for this instance. For the default Lifetime service this will be an object of type ILease.
InitializeLifetimeService
Objects can provide their own lease and so control their own lifetime. They do this by overriding the InitializeLifetimeService method provided on MarshalByRefObject.
OpenFile
Opens the file selected by the user, with read-only permission. The file is specified by the FileName property.
Reset
Overridden. Resets all properties to their default values.

Public Instance Events

Disposed
Represents the method which will handle the Disposed event of a Component
FileOk
Occurs when the user clicks on the Open or Save button on a file dialog box.
HelpRequest
Occurs when the user clicks the Help button on a common dialog box.

2. FontDialog

On click of the second button ‘FontDIalog’, an object of FontDialog class is defined and initialized. The following properties of the object have been used

ShowColor
Gets or sets a value indicating whether the dialog box displays the color choice.
AllowScriptChange
Gets or sets a value indicating whether the user can change the character set specified in the Script combo box to display a character set other than the one currently displayed.
Font
Gets or sets the selected font.

The dialog box looks like this:


Color Property is disabled from here
Selected
properties
DialogObjects202.jpg



private void btnFontDialog_Click(object sender, System.EventArgs e)
{
FontDialog fontDialog1 = new FontDialog();
fontDialog1.ShowColor = true;
fontDialog1.AllowScriptChange = true;
fontDialog1.ShowColor = false;
if(fontDialog1.ShowDialog() != DialogResult.Cancel )
{
fnt = fontDialog1.Font;
showInfo();
}
}

Other Public Instance Properties

AllowVerticalFonts
Gets or sets a value indicating whether the dialog box displays both vertical and horizontal fonts or only horizontal fonts.
Color
Gets or sets the selected font color.
FontMustExist
Gets or sets a value indicating whether the dialog box specifies an error condition if the user attempts to select a font or style that does not exist.
MaxSize
Gets or sets the maximum point size a user can select.
MinSize
Gets or sets the minimum point size a user can select.
ScriptsOnly
Gets or sets a value indicating whether the dialog box allows selection of fonts for all non-OEM and Symbol character sets, as well as the ANSI character set.
ShowApply
Gets or sets a value indicating whether the dialog box contains an Apply button.
ShowEffects
Gets or sets a value indicating whether the dialog box contains controls that allow the user to specify strikethrough, underline, and text color options.
ShowHelp
Gets or sets a value indicating whether the dialog box displays a Help button.

Public Instance Methods

ShowDialog
Runs a common dialog box.
Dispose
Overloaded. Releases the resources used by the Component
Equals
Overloaded. Determines whether two Object instances are equal.
GetHashCode
Serves as a hash function for a particular type, suitable for use in hashing algorithms and data structures like a hash table.
GetLifetimeService
Retrieves a lifetime service object that controls the lifetime policy for this instance. For the default Lifetime service this will be an object of type ILease.
InitializeLifetimeService
Objects can provide their own lease and so control their own lifetime. They do this by overriding the InitializeLifetimeService method provided on MarshalByRefObject.
Reset
Overridden. Resets all dialog box options to their default values.

Public Instance Events

Apply
Occurs when the user clicks the Apply button in the font dialog box.
Disposed
Represents the method that will handle the Disposed event of a Component
HelpRequest
Occurs when the user clicks the Help button on a common dialog box.


3. ColorDialog


On click of the third button ‘ColorDIalog’, an object of ColorDialog class is defined and initialized. The following properties of the object have been used

AllowFullOpen
Gets or sets a value indicating whether the user can use the dialog box to define custom colors.
FullOpen
Gets or sets a value indicating whether the controls used to create custom colors are visible when the dialog box is opened
ShowHelp
Gets or sets a value indicating whether a Help button appears in the color dialog box.
Color
Gets or sets the color selected by the user.

The dialog box looks like this:


Selected font color
DialogObjects203.jpg

private void btnColorDialog_Click(object sender, System.EventArgs e)
{
ColorDialog ColorDialog1 = new ColorDialog();
ColorDialog1.AllowFullOpen = true ;
ColorDialog1.FullOpen = true;
ColorDialog1.ShowHelp = true ;
// Set the initial color select to the current text color,
// so that if the user cancels out we will restore the original color.
ColorDialog1.Color = Color.DarkBlue;
ColorDialog1.ShowDialog();
clr = ColorDialog1.Color;
showInfo();
}

Other Public Instance Properties


AnyColor
Gets or sets a value indicating whether the dialog box displays all available colors in the set of basic colors.
CustomColors
Gets or sets the set of custom colors shown in the dialog box.
SolidColorOnly
Gets or sets a value indicating whether the dialog box will restrict users to selecting solid colors only.

Public Instance Methods

ShowDialog
Runs a common dialog box.
Dispose
Overloaded. Releases the resources used by the Component
Equals
Overloaded. Determines whether two Object instances are equal.
GetHashCode
Serves as a hash function for a particular type, suitable for use in hashing algorithms and data structures like a hash table.
GetLifetimeService
Retrieves a lifetime service object that controls the lifetime policy for this instance. For the default Lifetime service this will be an object of type ILease.
InitializeLifetimeService
Objects can provide their own lease and so control their own lifetime. They do this by overriding the InitializeLifetimeService method provided on MarshalByRefObject.
Reset
Overridden. Resets all options to their default values, the last selected color to black, and the custom colors to their default values.

Public Instance Events

Disposed
Represents the method which will handle the Disposed event of a Component
HelpRequest
Occurs when the user clicks the Help button on a common dialog box.



4. PrintPreview


On click of the ‘PrintPreview’ button, an object of PrintPreviewDialog class is defined and initialized.

PrintPreviewDialog control is a pre-configured dialog box used to display how a PrintDocument will appear when printed. It is used within the Windows application as a simple solution in lieu of configuring our own dialog box. The control contains buttons for printing, zooming in, displaying one or multiple pages, and closing the dialog box. In order to display the dialog box, its ShowDialog method is called. Certain properties are available through the PrintPreviewControl that the PrintPreviewDialog contains. We do not have to add PrintPreviewControl to the form. It was automatically contained within the PrintPreviewDialog when we added the dialog to our form.

Some of the properties available through the PrintPreviewControl are the Columns and Rows properties, which determine the number of pages displayed horizontally and vertically on the control.

The dialog box looks like this:


DialogObjects204.jpg

private void btnPrintPreview_Click(object sender, System.EventArgs e)

{

pd = new PrintDocument();

pd.PrintPage += new PrintPageEventHandler(this.pd_PrintPage);

PrintPreviewDialog printPreviewDialog1 = new PrintPreviewDialog();

printPreviewDialog1.Document = this.pd ;

printPreviewDialog1.FormBorderStyle = FormBorderStyle.Fixed3D ;

printPreviewDialog1.ShowDialog();

}



5. PrintDialog


On click of the button ‘PrintDIalog’, an object of PrintDialog class is defined and initialized. This dialog also requires the use of PrintDocument() component.

PrintDocument component is used to set the properties that describe what to print and then to print the document within Windows applications. It can be used in conjunction with the PrintDialog control to be in command of all aspects of document printing.

The dialog box looks like this:


DialogObjects205.jpg

private void btnPrintDialog_Click(object sender, System.EventArgs e)
{
PrintDialog PrintDialog1 = new PrintDialog();
pd = new PrintDocument();
pd.PrintPage += new PrintPageEventHandler(this.pd_PrintPage);
PrintDialog1.PrintToFile = false;
PrintDialog1.Document = pd;
if(PrintDialog1.ShowDialog() != DialogResult.Cancel )
{
try
{ pd.Print();
}
catch(Exception ex)
{ MessageBox.Show(ex.Message);
}
}
}

Public Instance Properties - PrintDialog


AllowPrintToFile
Gets or sets a value indicating whether the Print to file check box is enabled.
AllowSelection
Gets or sets a value indicating whether the From... To... Page option button is enabled.
AllowSomePages
Gets or sets a value indicating whether the Pages option button is enabled.
Container
Returns the IContainer that contains the Component
Document
Gets or sets a value indicating the PrintDocument used to obtain PrinterSettings
PrinterSettings
Gets or sets the PrinterSettings the dialog box to modify.
PrintToFile
Gets or sets a value indicating whether the Print to file check box is checked.
ShowHelp
Gets or sets a value indicating whether the Help button is displayed.
ShowNetwork
Gets or sets a value indicating whether the Network button is displayed.

Public Instance Methods – PrintDialog

ShowDialog
Runs a common dialog box.
Dispose
Overloaded. Releases the resources used by the Component
Equals
Overloaded. Determines whether two Object instances are equal.
GetHashCode
Serves as a hash function for a particular type, suitable for use in hashing algorithms and data structures like a hash table.
GetLifetimeService
Retrieves a lifetime service object that controls the lifetime policy for this instance. For the default Lifetime service this will be an object of type ILease.
InitializeLifetimeService
Objects can provide their own lease and so control their own lifetime. They do this by overriding the InitializeLifetimeService method provided on MarshalByRefObject.
Reset
Overridden. Resets all options, the last selected printer, and the page settings to their default values.

Public Instance Events– PrintDialog

Disposed
Represents the method which will handle the Disposed event of a Component
HelpRequest
Occurs when the user clicks the Help button on a common dialog box.

Properties – PrintDocument

DefaultPageSettings
Gets or sets the default settings that apply to a single, printed page of the document.
DocumentName
Gets or sets the document name to display (for example, in a print status dialog box or printer queue) while printing the document.
PrintController
Gets or sets the print controller that guides the printing process.
PrinterSettings
Gets or sets the printer that prints the document

Protected Instance Properties
DesignMode
Gets a value indicating whether the Component is currently in design mode.
Events
Gets the list of event handlers that are attached to this Component


6. SaveFileDialog

On click of the button ‘SaveFileDialog’, an object of SaveFileDialog class is defined and initialized. The following properties of the object (inherited from FileDialog) have been used in our example.

Filter
Gets or sets the current file name filter string, which determines the choices that appear in the "Save as file type" or "Files of type" box in the dialog box.
FilterIndex
Gets or sets the index of the filter currently selected in the file dialog box.
RestoreDirectory
Gets or sets a value indicating whether the dialog box restores the current directory before closing.

The dialog box looks like this:


DialogObjects206.jpg

private void btnSaveFileDialog_Click(object sender, System.EventArgs e)
{
Stream myStream ;
SaveFileDialog saveFileDialog1 = new SaveFileDialog();
saveFileDialog1.Filter = "txt files (*.txt)|*.txt|All files (*.*)|*.*" ;
saveFileDialog1.FilterIndex = 2 ;
saveFileDialog1.RestoreDirectory = true ;
if(saveFileDialog1.ShowDialog() == DialogResult.OK)
{
if((myStream = saveFileDialog1.OpenFile()) != null)
{
// Code to write the stream goes here:
sr.BaseStream.Seek(0,SeekOrigin.Begin);
int i;
while((i=sr.BaseStream.ReadByte()) != -1)
myStream.WriteByte((byte)i);
myStream.Close();
sr.BaseStream.Seek(0,SeekOrigin.Begin);
//revert at the beginning
}
}

}

Public Instance Properties


AddExtension
Gets or sets a value indicating whether the dialog box automatically adds an extension to a file name if the user omits the extension.
CheckFileExists
Gets or sets a value indicating whether the dialog box displays a warning if the user specifies a file name that does not exist.
CheckPathExists
Gets or sets a value indicating whether the dialog box displays a warning if the user specifies a path that does not exist.
Container
Returns the IContainer that contains the Component
CreatePrompt
Gets or sets a value indicating whether the dialog box prompts the user for permission to create a file if the user specifies a file that does not exist.
DefaultExt
Gets or sets the default file extension.
DereferenceLinks
Gets or sets a value indicating whether the dialog box returns the location of the file referenced by the shortcut or whether it returns the location of the shortcut (.lnk).
FileName
Gets or sets a string containing the file name selected in the file dialog box.
FileNames
Gets the file names of all selected files in the dialog box.
InitialDirector
Gets or sets the initial directory displayed by the file dialog box.
OverwritePrompt
Gets or sets a value indicating whether the Save As dialog box displays a warning if the user specifies a file name that already exists.
ShowHelp
Gets or sets a value indicating whether the Help button is displayed in the file dialog.
Title
Gets or sets the file dialog box title.
ValidateNames
Gets or sets a value indicating whether the dialog box accepts only valid Win32 file names.

Public Instance Methods

ShowDialog
Runs a common dialog box.
OpenFile
Opens the file with read/write permission selected by the user.
CreateObjRef
[To be supplied.]
Dispos
Overloaded. Releases the resources used by the Component
Equals
Overloaded. Determines whether two Object instances are equal.
GetHashCode
Serves as a hash function for a particular type, suitable for use in hashing algorithms and data structures like a hash table.
GetLifetimeService
Retrieves a lifetime service object that controls the lifetime policy for this instance. For the default Lifetime service this will be an object of type ILease.
InitializeLifetimeService
Objects can provide their own lease and so control their own lifetime. They do this by overriding the InitializeLifetimeService method provided on MarshalByRefObject.
Reset
Overridden. Resets all dialog box options to their default values.

Public Instance Events

Disposed (inherited from Component)
Represents the method which will handle the Disposed event of a Component
FileOk (inherited from FileDialog)
Occurs when the user clicks on the Open or Save button on a file dialog box.
HelpRequest (inherited from CommonDialog)
Occurs when the user clicks the Help button on a common dialog box.


The complete listing


using System;
using System.IO;
using System.Text;
using System.Drawing;
using System.Drawing.Printing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using System.Data;

namespace WindowsApplication2
{
public class frmTestingDialogObjects : System.Windows.Forms.Form
{
private System.Windows.Forms.Button btnOpenFileDialog;
private System.Windows.Forms.Button btnSaveFileDialog;
private System.Windows.Forms.Button btnColorDialog;
private System.Windows.Forms.Button btnFontDialog;
private System.Windows.Forms.Button btnPrintDialog;
private System.Windows.Forms.Label lblOutputData;
private System.Windows.Forms.Label lblCaption;
private Font fnt;
private Color clr;
private string fName;
private StreamReader sr;
private PrintDocument pd;
private System.Windows.Forms.Button btnPrintPreview;
private System.ComponentModel.Container components = null;

public frmTestingDialogObjects()
{
InitializeComponent();
}

protected override void Dispose( bool disposing )
{
if( disposing )
{
if (components != null)
{
components.Dispose();
}
}
base.Dispose( disposing );
}

#region Windows Form Designer generated code
private void InitializeComponent()
{
this.btnColorDialog = new System.Windows.Forms.Button();
this.btnFontDialog = new System.Windows.Forms.Button();
this.lblCaption = new System.Windows.Forms.Label();
this.btnOpenFileDialog = new System.Windows.Forms.Button();
this.btnSaveFileDialog = new System.Windows.Forms.Button();
this.btnPrintDialog = new System.Windows.Forms.Button();
this.lblOutputData = new System.Windows.Forms.Label();
this.btnPrintPreview = new System.Windows.Forms.Button();
this.SuspendLayout();
//
// btnColorDialog
//
this.btnColorDialog.Location = new System.Drawing.Point(16, 88);
this.btnColorDialog.Name = "btnColorDialog";
this.btnColorDialog.Size = new System.Drawing.Size(240, 24);
this.btnColorDialog.TabIndex = 0;
this.btnColorDialog.Text = "ColorDialog";
this.btnColorDialog.Click += new
System.EventHandler(this.btnColorDialog_Click);
//
// btnFontDialog
//
this.btnFontDialog.Location = new System.Drawing.Point(16, 56);
this.btnFontDialog.Name = "btnFontDialog";
this.btnFontDialog.Size = new System.Drawing.Size(240, 24);
this.btnFontDialog.TabIndex = 0;
this.btnFontDialog.Text = "FontDialog";
this.btnFontDialog.Click += new System.EventHandler(this.btnFontDialog_Click);
//
// lblCaption
//
this.lblCaption.Font = new System.Drawing.Font("Microsoft Sans Serif",
8.25F, System.Drawing.FontStyle.Bold,
System.Drawing.GraphicsUnit.Point, ((System.Byte)(0)));
this.lblCaption.Location = new System.Drawing.Point(304, 8);
this.lblCaption.Name = "lblCaption";
this.lblCaption.Size = new System.Drawing.Size(192, 16);
this.lblCaption.TabIndex = 2;
this.lblCaption.Text = "Output Data";
//
// btnOpenFileDialog
//
this.btnOpenFileDialog.Location = new System.Drawing.Point(16, 24);
this.btnOpenFileDialog.Name = "btnOpenFileDialog";
this.btnOpenFileDialog.Size = new System.Drawing.Size(240, 24);
this.btnOpenFileDialog.TabIndex = 0;
this.btnOpenFileDialog.Text = "OpenFileDialog";
this.btnOpenFileDialog.Click += new
System.EventHandler(this.btnOpenFileDialog_Click);
//
// btnSaveFileDialog
//
this.btnSaveFileDialog.Location = new System.Drawing.Point(16, 184);
this.btnSaveFileDialog.Name = "btnSaveFileDialog";
this.btnSaveFileDialog.Size = new System.Drawing.Size(240, 24);
this.btnSaveFileDialog.TabIndex = 0;
this.btnSaveFileDialog.Text = "SaveFileDialog";
this.btnSaveFileDialog.Click += new
System.EventHandler(this.btnSaveFileDialog_Click);
//
// btnPrintDialog
//
this.btnPrintDialog.Location = new System.Drawing.Point(16, 152);
this.btnPrintDialog.Name = "btnPrintDialog";
this.btnPrintDialog.Size = new System.Drawing.Size(240, 24);
this.btnPrintDialog.TabIndex = 0;
this.btnPrintDialog.Text = "PrintDialog";
this.btnPrintDialog.Click += new
System.EventHandler(this.btnPrintDialog_Click);
//
// lblOutputData
//
this.lblOutputData.BorderStyle =
System.Windows.Forms.BorderStyle.Fixed3D;
this.lblOutputData.Location = new System.Drawing.Point(304, 24);
this.lblOutputData.Name = "lblOutputData";
this.lblOutputData.Size = new System.Drawing.Size(344, 184);
this.lblOutputData.TabIndex = 1;
//
// btnPrintPreview
//
this.btnPrintPreview.Location = new System.Drawing.Point(16, 120);
this.btnPrintPreview.Name = "btnPrintPreview";
this.btnPrintPreview.Size = new System.Drawing.Size(240, 24);
this.btnPrintPreview.TabIndex = 0;
this.btnPrintPreview.Text = "PrintPreview";
this.btnPrintPreview.Click += new
System.EventHandler(this.btnPrintPreview_Click);
//
// frmTestingDialogObjects
//
this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);
this.ClientSize = new System.Drawing.Size(664, 229);
this.Controls.AddRange(new System.Windows.Forms.Control[] {
this.btnPrintPreview,
this.lblCaption,
this.lblOutputData,
this.btnSaveFileDialog,
this.btnOpenFileDialog,
this.btnColorDialog,
this.btnFontDialog,
this.btnPrintDialog});
this.Name = "frmTestingDialogObjects";
this.Text = "Testing Dilog Objects...";
this.ResumeLayout(false);
}
#endregion

[STAThread]
static void Main()
{
Application.Run(new frmTestingDialogObjects());
}
private void btnOpenFileDialog_Click(object sender, System.EventArgs e)
{
OpenFileDialog openFileDialog1 = new OpenFileDialog();
openFileDialog1.InitialDirectory = "c:\" ;
openFileDialog1.Filter= "txt files (*.txt)|*.txt|All files (*.*)|*.*" ;
openFileDialog1.FilterIndex = 2 ;
openFileDialog1.RestoreDirectory = true ;
if(openFileDialog1.ShowDialog() == DialogResult.OK)
{
fName = openFileDialog1.FileName;
showInfo();
sr = new StreamReader(fName);
}
}


private void btnSaveFileDialog_Click(object sender, System.EventArgs e)
{
Stream myStream ;
SaveFileDialog saveFileDialog1 = new SaveFileDialog();
saveFileDialog1.Filter= "txt files (*.txt)|*.txt|All files(*.*)|*.*" ;
saveFileDialog1.FilterIndex = 2 ;
saveFileDialog1.RestoreDirectory = true ;
if(saveFileDialog1.ShowDialog() == DialogResult.OK)
{
if((myStream = saveFileDialog1.OpenFile()) != null)
{
sr.BaseStream.Seek(0,SeekOrigin.Begin);
int i;
while((i=sr.BaseStream.ReadByte()) != -1)
myStream.WriteByte((byte)i);
myStream.Close();
sr.BaseStream.Seek(0,SeekOrigin.Begin);
}
}
}

private void btnColorDialog_Click(object sender, System.EventArgs e)
{
ColorDialog ColorDialog1 = new ColorDialog();
ColorDialog1.AllowFullOpen = true ;
ColorDialog1.FullOpen = true;
// Allow the user to get help. (default is false)
ColorDialog1.ShowHelp = true ;
// Set the initial color select to the current text color,
// so that if the user cancels out we will restore the original color.
ColorDialog1.Color = Color.DarkBlue;
ColorDialog1.ShowDialog();
clr = ColorDialog1.Color;
showInfo();
}

private void btnFontDialog_Click(object sender, System.EventArgs e)
{
FontDialog fontDialog1 = new FontDialog();
fontDialog1.ShowColor = true;
fontDialog1.AllowScriptChange = true;
fontDialog1.ShowColor = false;
if(fontDialog1.ShowDialog() != DialogResult.Cancel )
{
fnt = fontDialog1.Font;
showInfo();
}
}

private void btnPrintDialog_Click(object sender, System.EventArgs e)
{
PrintDialog PrintDialog1 = new PrintDialog();

pd = new PrintDocument();
pd.PrintPage += new PrintPageEventHandler(this.pd_PrintPage);
PrintDialog1.PrintToFile = false;
PrintDialog1.Document = pd;
//PrintDialog1.Document.PrinterSettings.PaperSizes.
if(PrintDialog1.ShowDialog() != DialogResult.Cancel )
{
try
{
pd.Print();
}
catch(Exception ex)
{
MessageBox.Show(ex.Message);
}
}
}

private void showInfo()
{
lblOutputData.Text = "File Name: " + fName.ToString() + "\n\r\n\r";
lblOutputData.Text = lblOutputData.Text + "Color : " +
clr.ToString() + "\n\r\n\r";
lblOutputData.Text = lblOutputData.Text + "Font : " + fnt +
"\n\r\n\r";
}

private void pd_PrintPage(object sender, PrintPageEventArgs ev)
{
float linesPerPage = 0;
float yPos = 0;
int count = 0;
float leftMargin = ev.MarginBounds.Left;
float topMargin = ev.MarginBounds.Top;
string line = null;
SolidBrush b = new SolidBrush(clr);
linesPerPage = ev.MarginBounds.Height / fnt.GetHeight(ev.Graphics);
while(count < linesPerPage && ((line=sr.ReadLine()) != null))
{
yPos = topMargin + (count * fnt.GetHeight(ev.Graphics));
ev.Graphics.DrawString(line, fnt, b, leftMargin, yPos, new
StringFormat());
count++;
}
if(line != null)ev.HasMorePages = true;
else ev.HasMorePages = false;
}

private void btnPrintPreview_Click(object sender, System.EventArgs e)
{
pd = new PrintDocument();
pd.PrintPage += new PrintPageEventHandler(this.pd_PrintPage);
PrintPreviewDialog printPreviewDialog1 = new PrintPreviewDialog();
printPreviewDialog1.Document = this.pd ;
printPreviewDialog1.FormBorderStyle = FormBorderStyle.Fixed3D ;
printPreviewDialog1.ShowDialog();
}
}
}


References:

1. Professional C# by Simon Robinson et al.
2. MSDN Documentation