Dialog Objects in .NET
.NET environment has provided us with variousclasses to use the Dialog objects. This paper explains how to create and use thefollowing dialog boxes in .NET environment:
- OpenFileDialog
- FontDialog
- ColorDialog
- PrintPreviewDialog
- PrintDialog
- SaveFileDialog
Object hierarchyof the above dialog objects is givenas
Object
MarshalByRefObject
Component
CommonDialog
ColorDialog
FileDialog
OpenFileDialog
SaveFileDialog
FontDialog
PrintDialog
Inthis example we have created an application that opens a dialog box to open atxt tile using a OpenFileDialog button. On click of FontDialog button, FontDialog 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 thefont. PrintPreview button helps the user preview the formatted document.PrintDialog button helps the user print the document. With the help ofSaveDialog button, the user can open ‘Save As’ dialog box to savethe copy of the file as a new file. All the selected parameters are displayedwith the help of a label. A runtime view of the FORM created is givebelow.

1. OpenFileDialog
On click of the first button, an object ofOpenFileDialog class is defined and initialized. The following properties of theobject (inherited from FileDialog) have been used.
|
InitialDirectory
|
Gets or sets the initial directory displayed bythe file dialog box.
|
|
Filter
|
Gets or sets the current file name filterstring, which determines the choices that appear in the “Save as filetype” or “Files of type” box in the dialogbox.
|
|
FilterIndex
|
Gets or sets the index of the filter currentlyselected in the file dialog box.
|
|
RestoreDirectory
|
Gets or sets a value indicating whether thedialog box restores the current directory before closing.
|
|
FileName
|
Gets or sets a string containing the file nameselected in the file dialog box.
|
The dialog box looks like this:
This is default directory
Filter applied to this field
File to beopened
private voidbtnOpenFileDialog_Click(object sender, System.EventArgse)
{
OpenFileDialogopenFileDialog1 = newOpenFileDialog();
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= newStreamReader(fName);
}
}
OtherPublic Instance Properties (inherited from FileDialog) are listedbelow
|
AddExtension
|
Gets or sets a value indicating whether thedialog box automatically adds an extension to a file name if the user omits theextension.
>/> |
|
CheckPathExists
|
Gets or sets a value indicating whether thedialog box displays a warning if the user specifies a path that does notexist.
|
|
DefaultExt
|
Gets or sets the default fileextension.
|
|
DereferenceLinks
|
Gets or sets a value indicating whether thedialog box returns the location of the file referenced by the shortcut orwhether it returns the location of the shortcut
|
|
FileNames
|
Gets the file names of all selected files inthe dialog box.
|
|
ShowHelp
|
Gets or sets a value indicating whether theHelp button is displayed in the file dialog.
|
|
Title
|
Gets or sets the file dialog boxtitle.
|
|
ValidateNames
|
Gets or sets a value indicating whether thedialog box accepts only valid Win32 file names.
|
Public InstanceMethods
|
ShowDialog
|
Runs a common dialog box. Only this method hasbeen used in our example.
|
|
Dispose
|
Overloaded. Releases the resources used by theComponent
|
|
Equals
|
Overloaded. Determines whether two Objectinstances are equal.
|
|
GetHashCode
|
Serves as a hash function for a particulartype, suitable for use in hashing algorithms and data structures like a hashtable.
|
|
GetLifetimeService
|
Retrieves a lifetime service object thatcontrols the lifetime policy for this instance. For the default Lifetime servicethis will be an object of type ILease.
|
|
InitializeLifetimeService
|
Objects can provide their own lease and socontrol their own lifetime. They do this by overriding theInitializeLifetimeService method provided onMarshalByRefObject.
|
|
OpenFile
|
Opens the file selected by the user, withread-only permission. The file is specified by the FileNameproperty.
|
|
Reset
|
Overridden. Resets all properties to theirdefault values.
|
Public Instance Events
|
Disposed
|
Represents the method which will handle theDisposed event of a Component
|
|
FileOk
|
Occurs when the user clicks on the Open or Savebutton on a file dialog box.
|
|
HelpRequest
|
Occurs when the user clicks the Help button ona common dialog box.
|
2.FontDialog
On click of the secondbutton ‘FontDIalog’, an object of FontDialog class is defined andinitialized. The following properties of the object have beenused
|
ShowColor
|
Gets or sets a value indicating whether thedialog box displays the color choice.
|
|
AllowScriptChange
|
Gets or sets a value indicating whether theuser can change the character set specified in the Script combo box todisplay a character set other than the one currently displayed.
|
|
Font
|
Gets or sets the selectedfont.
|
The dialog box looks like this:
Color Property is disabled from here
Selected
properties
private voidbtnFontDialog_Click(object sender, System.EventArgse)
{
FontDialogfontDialog1 = newFontDialog();
fontDialog1.ShowColor=true;
fontDialog1.AllowScriptChange=true;
fontDialog1.ShowColor=false;
if(fontDialog1.ShowDialog()!= DialogResult.Cancel)
{
fnt=fontDialog1.Font;
showInfo();
}
}
OtherPublic Instance Properties
|
AllowVerticalFonts
|
Gets or sets a value indicating whether thedialog box displays both vertical and horizontal fonts or only horizontalfonts.
|
|
Color
|
Gets or sets the selected fontcolor.
|
|
FontMustExist
|
Gets or sets a value indicating whether thedialog box specifies an error condition if the user attempts to select a font orstyle that does not exist.
|
|
MaxSize
|
Gets or sets the maximum point size a user canselect.
|
|
MinSize
|
Gets or sets the minimum point size a user canselect.
|
|
ScriptsOnly
|
Gets or sets a value indicating whether thedialog 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 thedialog box contains an Apply button.
|
|
ShowEffects
|
Gets or sets a value indicating whether thedialog box contains controls that allow the user to specify strikethrough,underline, and text color options.
|
|
ShowHelp
|
Gets or sets a value indicating whether thedialog box displays a Help button.
|
Public Instance Methods
|
ShowDialog
|
Runs a common dialog box.
|
|
Dispose
|
Overloaded. Releases the resources used by theComponent
|
|
Equals
|
Overloaded. Determines whether two Objectinstances are equal.
|
|
GetHashCode
|
Serves as a hash function for a particulartype, suitable for use in hashing algorithms and data structures like a hashtable.
|
|
GetLifetimeService
|
Retrieves a lifetime service object thatcontrols the lifetime policy for this instance. For the default Lifetime servicethis will be an object of type ILease.
|
|
InitializeLifetimeService
|
Objects can provide their own lease and socontrol their own lifetime. They do this by overriding theInitializeLifetimeService method provided onMarshalByRefObject.
|
|
Reset
|
Overridden. Resets all dialog box options totheir default values.
|
Public Instance Events
|
Apply
|
Occurs when the user clicks the Apply button inthe font dialog box.
|
|
Disposed
|
Represents the method that will handle theDisposed event of a Component
|
|
HelpRequest
|
Occurs when the user clicks the Help button ona common dialog box.
|
3.ColorDialog
On click of the third button‘ColorDIalog’, an object of ColorDialog class is defined andinitialized. The following properties of the object have beenused
|
AllowFullOpen
|
Gets or sets a value indicating whether theuser can use the dialog box to define custom colors.
|
|
FullOpen
|
Gets or sets a value indicating whether thecontrols used to create custom colors are visible when the dialog box isopened
|
|
ShowHelp
|
Gets or sets a value indicating whether a Helpbutton appears in the color dialog box.
|
|
Color
|
Gets or sets the color selected by theuser.
|
The dialog box looks like this:
Selected font color
private voidbtnColorDialog_Click(object sender, System.EventArgse)
{
ColorDialogColorDialog1 = newColorDialog();
ColorDialog1.AllowFullOpen= true;
ColorDialog1.FullOpen =true;
ColorDialog1.ShowHelp= true ;
// Set theinitial color select to the current textcolor,
// so that if theuser cancels out we will restore the originalcolor.
ColorDialog1.Color=Color.DarkBlue;
ColorDialog1.ShowDialog();
clr= ColorDialog1.Color;
showInfo();
}
Other Public InstanceProperties
|
AnyColor
|
Gets or sets a value indicating whether thedialog box displays all available colors in the set of basiccolors.
|
|
CustomColors
|
Gets or sets the set of custom colors shown inthe dialog box.
|
|
SolidColorOnly
|
Gets or sets a value indicating whether thedialog 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 theComponent
|
|
Equals
|
Overloaded. Determines whether two Objectinstances are equal.
|
|
GetHashCode
|
Serves as a hash function for a particulartype, suitable for use in hashing algorithms and data structures like a hashtable.
|
|
GetLifetimeService
|
Retrieves a lifetime service object thatcontrols the lifetime policy for thi
s instance. For the default Lifetime servicethis will be an object of type ILease. |
|
InitializeLifetimeService
|
Objects can provide their own lease and socontrol their own lifetime. They do this by overriding theInitializeLifetimeService method provided onMarshalByRefObject.
|
|
Reset
|
Overridden. Resets all options to their defaultvalues, the last selected color to black, and the custom colors to their defaultvalues.
|
Public Instance Events
|
Disposed
|
Represents the method which will handle theDisposed event of a Component
|
|
HelpRequest
|
Occurs when the user clicks the Help button ona common dialog box.
|
4.PrintPreview
On click of the ‘PrintPreview’ button,an object of PrintPreviewDialog class is defined and initialized.
PrintPreviewDialog control is apre-configured dialog box used to display how a PrintDocument will appear whenprinted. It is used within the Windows application as a simple solution in lieuof configuring our own dialog box. The control contains buttons for printing,zooming in, displaying one or multiple pages, and closing the dialog box. Inorder to display the dialog box, its ShowDialog method is called. Certainproperties are available through the PrintPreviewControl that thePrintPreviewDialog contains. We do not have to addPrintPreviewControl to the form. It was automatically contained withinthe PrintPreviewDialog when we added the dialog to our form.
Some of the properties available through thePrintPreviewControl are the Columns and Rows properties,which determine the number of pages displayed horizontally and vertically on thecontrol.
The dialog box looks like this:
private voidbtnPrintPreview_Click(object sender, System.EventArgs e)
{
pd = newPrintDocument();
pd.PrintPage +=new PrintPageEventHandler(this.pd_PrintPage);
PrintPreviewDialogprintPreviewDialog1 = new PrintPreviewDialog();
printPreviewDialog1.Document= this.pd ;
printPreviewDialog1.FormBorderStyle= FormBorderStyle.Fixed3D ;
printPreviewDialog1.ShowDialog();
}
5.PrintDialog
On click of the button ‘PrintDIalog’, anobject of PrintDialog class is defined and initialized. This dialog alsorequires the use of PrintDocument()component.
PrintDocument component isused to set the properties that describe what to print and then to print thedocument within Windows applications. It can be used in conjunction with thePrintDialog control to be in command of all aspects of documentprinting.
The dialog box looks like this:
private voidbtnPrintDialog_Click(object sender, System.EventArgs e)
{
PrintDialogPrintDialog1 = 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 thePrint to file check box is enabled.
|
|
AllowSelection
|
Gets or sets a value indicating whether theFrom… To… Page option button is enabled.
|
|
AllowSomePages
|
>Gets or sets a value indicating whether thePages option button is enabled. |
|
Container
|
Returns the IContainer that contains theComponent
|
|
Document
|
Gets or sets a value indicating thePrintDocument used to obtain PrinterSettings
|
|
PrinterSettings
|
Gets or sets the PrinterSettings the dialog boxto modify.
|
|
PrintToFile
|
Gets or sets a value indicating whether thePrint to file check box is checked.
|
|
ShowHelp
|
Gets or sets a value indicating whether theHelp button is displayed.
|
|
ShowNetwork
|
Gets or sets a value indicating whether theNetwork button is displayed.
|
Public Instance Methods –PrintDialog
|
ShowDialog
|
Runs a common dialog box.
|
|
Dispose
|
Overloaded. Releases the resources used by theComponent
|
|
Equals
|
Overloaded. Determines whether two Objectinstances are equal.
|
|
GetHashCode
|
Serves as a hash function for a particulartype, suitable for use in hashing algorithms and data structures like a hashtable.
|
|
GetLifetimeService
|
Retrieves a lifetime service object thatcontrols the lifetime policy for this instance. For the default Lifetime servicethis will be an object of type ILease.
|
|
InitializeLifetimeService
|
Objects can provide their own lease and socontrol their own lifetime. They do this by overriding theInitializeLifetimeService method provided onMarshalByRefObject.
|
|
Reset
|
Overridden. Resets all options, the lastselected printer, and the page settings to their defaultvalues.
|
Public Instance Events–PrintDialog
|
Disposed
|
Represents the method which will handle theDisposed event of a Component
|
|
HelpRequest
|
Occurs when the user clicks the Help button ona common dialog box.
|
Properties –PrintDocument
|
DefaultPageSettings
|
Gets or sets the default settings that applyto 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 thedocument.
|
|
PrintController
|
Gets or sets the print controller that guidesthe printing process.
|
|
PrinterSettings
|
Gets or sets the printer that prints thedocument
|
|
Protected InstanceProperties
|
|
|
DesignMode
|
Gets a value indicating whether the Componentis currently in design mode.
|
|
Events
|
Gets
the list of event handlers that areattached to this Component |
6.SaveFileDialog
On click of the button‘SaveFileDialog’, an object of SaveFileDialog class is defined andinitialized. The following properties of the object(inherited from FileDialog)have been used in our example.
|
Filter
|
Gets or sets the current file name filterstring, 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 currentlyselected in the file dialog box.
|
|
RestoreDirectory
|
Gets or sets a value indicating whether thedialog box restores the current directory before closing.
|
The dialog box looks like this:
private voidbtnSaveFileDialog_Click(object sender, System.EventArgse)
{
StreammyStream ;
SaveFileDialogsaveFileDialog1 = newSaveFileDialog();
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 goeshere:
sr.BaseStream.Seek(0,SeekOrigin.Begin);
inti;
while((i=sr.BaseStream.ReadByte())!=-1)
myStream.WriteByte((byte)i);
myStream.Close();
sr.BaseStream.Seek(0,SeekOrigin.Begin);
//revertat thebeginning
}
}
}
Public InstanceProperties
|
AddExtension
|
Gets or sets a value indicating whether thedialog box automatically adds an extension to a file name if the user omits theextension.
|
|
CheckFileExists
|
Gets or sets a value indicating whether thedialog box displays a warning if the user specifies a file name that does notexist.
|
|
CheckPathExists
|
Gets or sets a value indicating whether thedialog box displays a warning if the user specifies a path that does notexist.
|
|
Container
|
Returns the IContainer that contains theComponent
|
|
CreatePrompt
|
Gets or sets a value indicating whether thedialog box prompts the user for permission to create a file if the userspecifies a file that does not exist.
|
|
DefaultExt
|
Gets or sets the default fileextension.
|
|
DereferenceLinks
|
Gets or sets a value indicating whether thedialog box returns the location of the file referenced by the shortcut orwhether it returns the location of the shortcut (.lnk).
|
|
FileName
|
Gets or sets a string containing the file nameselected in the file dialog box.
|
|
FileNames
|
Gets the file names of all selected f
iles inthe dialog box. |
|
InitialDirector
|
Gets or sets the initial directory displayed bythe file dialog box.
|
|
OverwritePrompt
|
Gets or sets a value indicating whether theSave As dialog box displays a warning if the user specifies a file name thatalready exists.
|
|
ShowHelp
|
Gets or sets a value indicating whether theHelp button is displayed in the file dialog.
|
|
Title
|
Gets or sets the file dialog boxtitle.
|
|
ValidateNames
|
Gets or sets a value indicating whether thedialog box accepts only valid Win32 file names.
|
Public Instance Methods
|
ShowDialog
|
Runs a common dialog box.
|
|
OpenFile
|
Opens the file with read/write permissionselected by the user.
|
|
CreateObjRef
|
[To be supplied.]
|
|
Dispos
|
Overloaded. Releases the resources used by theComponent
|
|
Equals
|
Overloaded. Determines whether twoObject instances are equal.
|
|
GetHashCode
|
Serves as a hash function for a particulartype, suitable for use in hashing algorithms and data structures like a hashtable.
|
|
GetLifetimeService
|
Retrieves a lifetime service object thatcontrols the lifetime policy for this instance. For the default Lifetime servicethis will be an object of type ILease.
|
|
InitializeLifetimeService
|
Objects can provide their own lease and socontrol their own lifetime. They do this by overriding theInitializeLifetimeService method provided onMarshalByRefObject.
|
|
Reset
|
Overridden. Resets all dialog box options totheir default values.
|
Public InstanceEvents
|
Disposed (inherited fromComponent)
|
Represents the method which will handle theDisposed event of a Component
|
|
FileOk (inherited fromFileDialog)
|
Occurs when the user clicks on the Open or Savebutton on a file dialog box.
|
|
HelpRequest (inherited fromCommonDialog)
|
Occurs when the user clicks the Help button ona common dialog box.
|
The completelisting
usingSystem;
usingSystem.IO;
usingSystem.Text;
usingSystem.Drawing;
usingSystem.Drawing.Printing;
usingSystem.Collections;
usingSystem.ComponentModel;
usingSystem.Windows.Forms;
usingSystem.Data;
namespaceWindowsApplication2
{
publicclass frmTestingDialogObjects :System.Windows.Forms.Form
{
privateSystem.Windows.Forms.ButtonbtnOpenFileDialog;
privateSystem.Windows.Forms.ButtonbtnSaveFileDialog;
privateSystem.Windows.Forms.ButtonbtnColorDialog;
privateSystem.Windows.Forms.ButtonbtnFontDialog;
privateSystem.Windows.Forms.ButtonbtnPrintDialog;
privateSystem.Windows.Forms.LabellblOutputData;
privateSystem.Windows.Forms.LabellblCaption;
private Fontfnt;
private Colorclr;
private stringfName;
privateStreamReader sr;
privatePrintDocument pd;
privateSystem.Windows.Forms.ButtonbtnPrintPreview;
privateSystem.ComponentModel.Container components =null;
publicfrmTestingDialogObjects()
{
InitializeComponent();
}
protectedoverride void Dispose( bool disposing)
{
if(disposing)
{
if(components !=null)
{
components.Dispose();
}
}
base.Dispose(disposing);
}
#regionWindows Form Designer generatedcode
private voidInitializeComponent()
{
this.btnColorDialog= newSystem.Windows.Forms.Button();
this.btnFontDialog= newSystem.Windows.Forms.Button();
this.lblCaption= newSystem.Windows.Forms.Label();
this.btnOpenFileDialog= newSystem.Windows.Forms.Button();
this.btnSaveFileDialog= newSystem.Windows.Forms.Button();
this.btnPrintDialog= newSystem.Windows.Forms.Button();
this.lblOutputData= newSystem.Windows.Forms.Label();
this.btnPrintPreview= newSystem.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+= newSystem.EventHandler(this.btnFontDialog_Click);
//
//lblCaption
//
this.lblCaption.Font= new System.Drawing.Font("Microsoft SansSerif",
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= "OutputData";
//
//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(newSystem.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 DilogObjects...";
this.ResumeLayout(false);
}
#endregion
[STAThread]
staticvoidMain()
{
Application.Run(newfrmTestingDialogObjects());
pan style="font-family:Courier New;font-size:x-small;"> }
privatevoid btnOpenFileDialog_Click(object sender, System.EventArgse)
{
OpenFileDialogopenFileDialog1 = newOpenFileDialog();
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= newStreamReader(fName);
}
}
privatevoid btnSaveFileDialog_Click(object sender, System.EventArgse)
{
StreammyStream;
SaveFileDialogsaveFileDialog1 = newSaveFileDialog();
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);
inti;
while((i=sr.BaseStream.ReadByte())!=-1)
myStream.WriteByte((byte)i);
myStream.Close();
sr.BaseStream.Seek(0,SeekOrigin.Begin);
}
}
}
privatevoid btnColorDialog_Click(object sender, System.EventArgse)
{
ColorDialogColorDialog1 = newColorDialog();
ColorDialog1.AllowFullOpen= true;
ColorDialog1.FullOpen= true;
// Allow theuser to get help. (default isfalse)
ColorDialog1.ShowHelp= true ;
// Set theinitial color select to the current textcolor,
// so that if theuser cancels out we will restore the originalcolor.
ColorDialog1.Color=Color.DarkBlue;
ColorDialog1.ShowDialog();
clr= ColorDialog1.Color;
showInfo();
}
privatevoid btnFontDialog_Click(object sender, System.EventArgse)
{
FontDialogfontDialog1 = newFontDialog();
fontDialog1.ShowColor=true;
fontDialog1.AllowScriptChange=true;
fontDialog1.ShowColor=false;
if(fontDialog1.ShowDialog()!= DialogResult.Cancel)
{
fnt=fontDialog1.Font;
showInfo();
}
}
privatevoid btnPrintDialog_Click(object sender, System.EventArgse)
{
PrintDialogPrintDialog1 = newPrintDialog();
pd =newPrintDocument();
pd.PrintPage+= newPrintPageEventHandler(this.pd_PrintPage);
PrintDialog1.PrintToFile=false;
PrintDialog1.Document=pd;
//PrintDialog1.Document.PrinterSettings.PaperSizes.
if(PrintDialog1.ShowDialog()!= DialogResult.Cancel)
{
try
{
pd.Print();
}
catch(Exceptionex)
{
MessageBox.Show(ex.Message);
}
}
}
privatevoidshowInfo()
{
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";
}
privatevoid pd_PrintPage(object sender, PrintPageEventArgsev)
{
float linesPerPage= 0;
float yPos =0;
int count =0;
float leftMargin =ev.MarginBounds.Left;
float topMargin=ev.MarginBounds.Top;
string line= null;
SolidBrush b =newSolidBrush(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;
elseev.HasMorePages =false;
}
privatevoid btnPrintPreview_Click(object sender, System.EventArgse)
{
pd= newPrintDocument();
pd.PrintPage+= newPrintPageEventHandler(this.pd_PrintPage);
PrintPreviewDialogprintPreviewDialog1 = newPrintPreviewDialog();
printPreviewDialog1.Document= this.pd;
printPreviewDialog1.FormBorderStyle= FormBorderStyle.Fixed3D;
printPreviewDialog1.ShowDialog();
}
}
}
References:
1.Professional C# by Simon Robinson etal.
2. MSDN Documentation












No comments yet... Be the first to leave a reply!