Export (0) Print
Expand All

Essential Code for Windows Forms Dialog Boxes

Visual Studio .NET 2003
 

Seth Grossman
Visual Studio Team
Microsoft Corporation

January 2002

Summary: The .NET Framework contains classes that represent the various dialogs that are frequently used in Microsoft Windows applications. However, the core functionality of a given dialog box (that is, OpenFileDialog, opening a file; SaveFileDialog, saving a file) has often not been implemented in the class. Within this document, the steps for implementing this functionality are described. (9 printed pages)

Contents

Introduction
OpenFileDialog Component
SaveFileDialog Component
ColorDialog Component
FontDialog Component
PrintDocument Class
PrintDialog Component
PageSetupDialog Component
PrintPreviewDialog Control
Conclusion

Introduction

The Windows Forms dialog components are the same dialog boxes found in the Microsoft® Windows® operating system; the PrintDialog component is the "Print" dialog box, the OpenFileDialog component is the "Open" dialog box, and so on.

Similar to previous systems of Windows programming and Microsoft Visual Basic® 6.0, the .NET Framework provides you with dialog boxes that will be immediately familiar to Windows users. Often, there are a variety of ways to accomplish the work of a given dialog box, such as printing a file with the Print dialog box. Thus, the mechanism to actually accomplish the task (print the file, choose the color) is not implemented as part of the class. This allows you to code a specific means of accomplishing these tasks as per the needs of your application. So the .NET Framework allows you to display the standard dialog boxes, but you write your own logic to respond to users' selections in the dialog boxes. This article provides example code for performing each component's ultimate purpose.

Note   For a complete list of the properties, methods, and events for each dialog component, see the Members page for that component's class. For example, if you were looking for the methods associated with the OpenFileDialog component, you could look in the documentation Index for "OpenFileDialog class, all members" and find the topic containing the pertinent information.

OpenFileDialog Component

This dialog presents users with a way to browse the folders of their computer or any computer on the network and allows them to open files. The dialog box returns the path and name of the file the user selected in the dialog box.

The OpenFileDialog component (and SaveFileDialog component, discussed in greater detail below) wraps all the functionality required to allow users to navigate the file system and select files. By using either of these components, you are saved the task of coding this functionality yourself; you can concentrate on opening and saving the files themselves.

Note   Be aware that the FileDialog class's FilterIndex property (which, due to inheritance, is part of both the OpenFileDialog and SaveFileDialog classes) uses a one-based index. This property is featured in some of the code samples below (and this fact is noted at those points as well). This is important if you are writing code to open a specific application based upon the file-type filter, or if you are saving data in a specific format (for example, saving a file in plain text versus binary format). Keep this in mind as you write code that features the FilterIndex property, as it is easy to forget.

The code below uses the Button control's Click event handler to open an instance of the OpenFileDialog component. When a file is chosen and the user clicks OK, the file selected in the dialog box opens. In this case, the file is opened in a message box, just to show that the file stream has been read.

The example assumes a Button control named Button1 and an OpenFileDialog component named OpenFileDialog1.

' Visual Basic
Private Sub Button1_Click(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles Button1.Click
   If OpenFileDialog1.ShowDialog() = DialogResult.OK Then
     Dim sr As New System.IO.StreamReader(OpenFileDialog1.FileName)
     MessageBox.Show(sr.ReadToEnd)
     sr.Close()
   End If
End Sub

// C#
private void button1_Click(object sender, System.EventArgs e)
{
   if(openFileDialog1.ShowDialog() == DialogResult.OK)
   {
     System.IO.StreamReader sr = new 
         System.IO.StreamReader(openFileDialog1.FileName);
     MessageBox.Show(sr.ReadToEnd());
     sr.Close();
   }
}
C# Note   Be sure that the necessary code to wire up the event handler is present. In this case, it would be similar to the following:
//C#
this.button1.Click += new System.EventHandler(this.button1_Click);

Another way to open a file is to use the OpenFileDialog component's OpenFile method, which returns the bytes that compose the file. In the example below, an OpenFileDialog component is instantiated with a "cursor" filter on it, allowing the user only to choose cursor files (files with the file extension .cur). If a .cur file is chosen, the form's cursor is set to the selected cursor.

The example assumes a Button control named Button1.

' Visual Basic
Private Sub Button1_Click(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles Button1.Click
' Display an OpenFileDialog so the user can select a Cursor.
   Dim openFileDialog1 As New OpenFileDialog()
   openFileDialog1.Filter = "Cursor Files|*.cur"
   openFileDialog1.Title = "Select a Cursor File"

   ' Show the Dialog.
   ' If the user clicked OK in the dialog and 
   ' a .CUR file was selected, open it.
   If openFileDialog1.ShowDialog() = DialogResult.OK Then
     If openFileDialog1.FileName <> "" Then
     ' Assign the cursor in the Stream to the Form's Cursor property.
       Me.Cursor = New Cursor(openFileDialog1.OpenFile())
     End If
   End If
End Sub

// C#
private void button1_Click(object sender, System.EventArgs e)
{
// Display an OpenFileDialog so the user can select a Cursor.
   OpenFileDialog openFileDialog1 = new OpenFileDialog();
   openFileDialog1.Filter = "Cursor Files|*.cur";
   openFileDialog1.Title = "Select a Cursor File";

   // Show the Dialog.
   // If the user clicked OK in the dialog and
   // a .CUR file was selected, open it.
   if (openFileDialog1.ShowDialog() == DialogResult.OK)
   {
     if(openFileDialog1.FileName != "")
     {
       // Assign the cursor in the Stream to the Form's Cursor property.
       this.Cursor = new Cursor(openFileDialog1.OpenFile());
     }
   }
}
C# Note   Be sure that the necessary code to wire up the event handler is present. In this case, it would be similar to the following:
//C#
this.button1.Click += new System.EventHandler(this.button1_Click);

For more information about reading from file streams, see FileStream.BeginRead Method.

SaveFileDialog Component

This dialog presents users with a way to browse the file system and select files to be saved. However, you must write the code to actually write the files out.

The code below uses the Button control's Click event handler to open an instance of the SaveFileDialog component. When a file is chosen and the user clicks OK, the content of the form's RichTextBox control is saved to the file selected in the dialog box.

The example assumes a Button control named Button1, a RichTextBox control named RichTextBox1, and a SaveFileDialog component named OpenFileDialog1.

' Visual Basic
Private Sub Button1_Click(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles Button1.Click
   If SaveFileDialog1.ShowDialog() = DialogResult.OK Then
     RichTextBox1.SaveFile(SaveFileDialog1.FileName, _
     RichTextBoxStreamType.PlainText)
   End If
End Sub

// C#
private void button1_Click(object sender, System.EventArgs e)
{
   if((saveFileDialog1.ShowDialog() == DialogResult.OK))
   {
     richTextBox1.SaveFile(saveFileDialog1.FileName, RichTextBoxStreamType.PlainText);
   }
}
C# Note   Be sure that the necessary code to wire up the event handler is present. In this case, it would be similar to the following:
//C#
this.button1.Click += new System.EventHandler(this.button1_Click);

Another way to save a file is to use the SaveFileDialog component's OpenFile method, which gives you a Stream object you can write to.

In the example below, there is a Button control with an image assigned to it. When you click the button, a SaveFileDialog component is instantiated with a filter that allows files of type .gif, .jpeg, and .bmp. If a file of this type is selected in the Save File dialog box, the button's image is saved.

The example assumes a Button control named Button2 with its Image property set to a file of type .gif, .jpeg, or .bmp.

'Visual Basic
Private Sub Button2_Click(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles Button2.Click
   ' Display an SaveFileDialog so the user can save the Image
   ' assigned to Button2.
   Dim saveFileDialog1 As New SaveFileDialog()
   saveFileDialog1.Filter = "JPeg Image|*.jpg|Bitmap Image|*.bmp|Gif Image|*.gif"
   saveFileDialog1.Title = "Save an Image File"
   saveFileDialog1.ShowDialog()
   
   ' If the file name is not an empty string open it for saving.
   If saveFileDialog1.FileName <> "" Then
     ' Save the Image via a FileStream created by the OpenFile method.
     Dim fs As System.IO.FileStream = Ctype _
        (saveFileDialog1.OpenFile(), System.IO.FileStream)
     ' Save the Image in the appropriate ImageFormat based upon the
     ' file type selected in the dialog box.
     ' NOTE that the FilterIndex property is one-based.
     Select Case saveFileDialog1.FilterIndex
       Case 1
          Me.button2.Image.Save(fs, _
             System.Drawing.Imaging.ImageFormat.Jpeg)

       Case 2
          Me.button2.Image.Save(fs, _
             System.Drawing.Imaging.ImageFormat.Bmp)

       Case 3
          Me.button2.Image.Save(fs, _
             System.Drawing.Imaging.ImageFormat.Gif)
     End Select

     fs.Close()
   End If
End Sub

// C#
private void button2_Click(object sender, System.EventArgs e)
{
   // Display an SaveFileDialog so the user can save the Image
   // assigned to Button2.
   SaveFileDialog saveFileDialog1 = new SaveFileDialog();
   saveFileDialog1.Filter = "JPeg Image|*.jpg|Bitmap Image|*.bmp|Gif Image|*.gif";
   saveFileDialog1.Title = "Save an Image File";
   saveFileDialog1.ShowDialog();

   // If the file name is not an empty string open it for saving.
   if(saveFileDialog1.FileName != "")
   {
     // Save the Image via a FileStream created by the OpenFile method.
     System.IO.FileStream fs = 
        (System.IO.FileStream)saveFileDialog1.OpenFile();
     // Save the Image in the appropriate ImageFormat based upon the
     // File type selected in the dialog box.
     // NOTE that the FilterIndex property is one-based.
     switch(saveFileDialog1.FilterIndex)
     {
       case 1 : 
       this.button2.Image.Save(fs, 
          System.Drawing.Imaging.ImageFormat.ImageFormat.Jpeg);
       break;

       case 2 : 
       this.button2.Image.Save(fs, 
          System.Drawing.Imaging.ImageFormat.ImageFormat.Bmp);
       break;

       case 3 : 
       this.button2.Image.Save(fs, 
          System.Drawing.Imaging.ImageFormat.Gif);
       break;
     }

   fs.Close();
   }
}
C# Note   Be sure that the necessary code to wire up the event handler is present. In this case, it would be similar to the following:
//C#
this.button2.Click += new System.EventHandler(this.button2_Click);

For more information about writing file streams, see FileStream.BeginWrite Method.

ColorDialog Component

This dialog box displays a list of colors and returns a property containing the color the user has selected.

Unlike the dialog components mentioned previously, the ColorDialog component gives you easy access to the main purpose of the dialog box (choosing a color). The color selected in the dialog box is returned in the Color property. Thus, taking advantage of the color selected by the user is as easy as setting a property. In the example below, the Button control's Click event handler opens a ColorDialog component. When a color is chosen and the user clicks OK, the button's background color is set to the chosen color. The example assumes a Button control named Button1 and a ColorDialog component named ColorDialog1.

' Visual Basic
Private Sub Button1_Click(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles Button1.Click
   If ColorDialog1.ShowDialog() = DialogResult.OK Then
     Button1.BackColor = ColorDialog1.Color
   End If
End Sub

// C#
private void button1_Click(object sender, System.EventArgs e)
{
   if(colorDialog1.ShowDialog() == DialogResult.OK)
   {
     button1.BackColor = colorDialog1.Color;
   }
}
C# Note   Be sure that the necessary code to wire up the event handler is present. In this case, it would be similar to the following:
//C#
this.button1.Click += new System.EventHandler(this.button1_Click);

Other properties you can specify on the ColorDialog component include the AllowFullOpen property, which, when set to false, disables the "Define Custom Colors" button so that the user is restricted to the predefined colors in the palette, and the SolidColorOnly property, which, when set to true, does not allow the user to select dithered colors.

FontDialog Component

This dialog allows the user to select a font in order to change its display aspects, such as its weight and size.

The font selected in the dialog box is returned in the Font property. Thus, taking advantage of the font selected by the user is as easy as setting a property. In the example below, the Button control's Click event handler opens a FontDialog component. When a font is chosen and the user clicks OK, the Font property of a TextBox control that is on the form is set to the chosen font. The example assumes a Button control named Button1, a TextBox control named TextBox1, and a FontDialog component named FontDialog1.

' Visual Basic
Private Sub Button1_Click(ByVal sender As System.Object, _
 ByVal e As System.EventArgs) Handles Button1.Click
   If FontDialog1.ShowDialog() = DialogResult.OK Then
     TextBox1.Font = FontDialog1.Font
   End If
End Sub

// C#
private void button1_Click(object sender, System.EventArgs e)
{
   if(fontDialog1.ShowDialog() == DialogResult.OK)
   {
     textBox1.Font = fontDialog1.Font;
   }
}
C# Note   Be sure that the necessary code to wire up the event handler is present. In this case, it would be similar to the following:
//C#
this.button1.Click += new System.EventHandler(this.button1_Click);

Other properties you can specify on the FontDialog component include the MinSize and MaxSize properties, which determine the minimum and maximum point size a user can select, and the ShowColor property, which, when set to true, displays a drop-down box within the dialog that allows the user to choose the color of the font.

PrintDocument Class

The next three dialog boxes discussed (PrintDialog and PageSetupDialog components and the PrintPreviewDialog control) all involve using the PrintDocument class. The PrintDocument class represents a document to be printed; you set properties on this class to specify its appearance and how it is to be printed and then instances of this class are sent to a printer. Frequently, you instantiate an instance of the PrintDocument class, set its properties in an instance of the PageSetupDialog component, view it prior to printing in an instance of the PrintPreviewDialog control, and finally print it from an instance of the PrintDialog component.

For more information about the PrintDocument class, see PrintDocument Class.

PrintDialog Component

This dialog presents users with a way to send documents to a printer to be printed. Additionally, it can be used to select a printer, choose the pages to print, and determine other print-related settings. With it you can give users flexibility in printing their documents: they can print all, print a selected page range, or print a selection.

An important aspect of working with the PrintDialog component is how it interacts with the PrinterSettings class. The PrinterSettings class is used to represent specific choices for the feature sets of printers such as paper sources, printer resolutions, and double-sized printing ability. Each of these settings is represented as a property of the PrinterSettings class. The PrintDialog class modifies these property values for a given instance of the PrinterSettings class that is associated with the document (and is represented as the PrintDocument.PrinterSettings property).

The PrintDialog component sends an instance of the PrintDocument class with certain printer settings to the selected printer. For an example of using the PrintDialog component to send material to a printer to be printed, see Creating Standard Windows Forms Print Jobs.

PageSetupDialog Component

The PageSetupDialog component is used to display layout, paper size, and other page layout choices to the user. You display the PageSetupDialog component just like all the other dialog boxes, using the ShowDialog method. Additionally, you need to specify an instance of the PrintDocument class; this is the document to be printed. Additionally, users must have a printer installed on their computer, either locally or through a network, as this is partly how the PageSetupDialog component determines the page formatting choices presented to the user.

An important aspect of working with the PageSetupDialog component is how it interacts with the PageSettings class. The PageSettings class is used to specify settings that modify the way a page will be printed, such as paper orientation, the size of the page, and the margins. Each of these settings is represented as a property of the PageSettings class. The PageSetupDialog class modifies these property values for a given instance of the PageSettings class that is associated with the document (and is represented as PrintDocument.DefaultPageSettings property).

In the code below, the Button control's Click event handler opens an instance of the PageSetupDialog component. An existing document is specified in the Document property, and its Color property is set to false.

The example assumes a Button control named Button1, a PrintDocument component named myDocument, and a PageSetupDialog component named PageSetupDialog1.

' Visual Basic
Private Sub Button1_Click(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles Button1.Click
   ' The print document 'myDocument' used below
   ' is merely for an example.
   'You will have to specify your own print document.
   PageSetupDialog1.Document = myDocument
   ' Set the print document's color setting to false,
   ' so that the page will not be printed in color.
   PageSetupDialog1.Document.DefaultPageSettings.Color = False
   PageSetupDialog1.ShowDialog()
End Sub

// C#
private void button1_Click(object sender, System.EventArgs e)
{
   // The print document 'myDocument' used below
   // is merely for an example.
   // You will have to specify your own print document.
   pageSetupDialog1.Document = myDocument;
   // Set the print document's color setting to false,
   // so that the page will not be printed in color.
   pageSetupDialog1.Document.DefaultPageSettings.Color = false;
   pageSetupDialog1.ShowDialog();
}
C# Note   Be sure that the necessary code to wire up the event handler is present. In this case, it would be similar to the following:
//C#
this.button1.Click += new System.EventHandler(this.button1_Click);

PrintPreviewDialog Control

Unlike other dialog boxes, which have an effect on your application or other controls, the PrintPreviewDialog control displays most of its functionality within the dialog box itself. This dialog box is used to display a document, often before it is to be printed.

You display the PrintPreviewDialog control just like all the other dialog boxes, using the ShowDialog method. Additionally, you need to specify an instance of the PrintDocument class; this is the document to be printed.

Note   When using the PrintPreviewDialog control, you must have a printer installed on your computer, either locally or through a network, as this is partly how the PrintPreviewDialog component determines how a document will look when printed.

As with the PrintDialog component, the PrintPreviewDialog control makes use of the PrinterSettings class. Additionally, the PrintPreviewDialog control makes use of the PageSettings class, just like the PageSetupDialog component. The print document specified in the PrintPreviewDialog control's Document property refers to instances of both the PrinterSettings and PageSettings classes, and these are used to render the document in the preview window.

In the code below, the Button control's Click event handler opens an instance of the PrintPreviewDialog control. The print document is specified in Document property. Note that in the example below, no print document is specified.

The example assumes a Button control named Button1, a PrintDocument component named myDocument, and a PrintPreviewDialog control named PrintPreviewDialog1.

' Visual Basic
Private Sub Button1_Click(ByVal sender As System.Object, _
 ByVal e As System.EventArgs) Handles Button1.Click
   ' The print document 'myDocument' used below
   ' is merely for an example.
   ' You will have to specify your own print document.
   PrintPreviewDialog1.Document = myDocument
   PrintPreviewDialog1.ShowDialog()
End Sub

// C#
private void button1_Click(object sender, System.EventArgs e)
{
   // The print document 'myDocument' used below
   // is merely for an example.
   // You will have to specify your own print document.
   printPreviewDialog1.Document = myDocument;
   printPreviewDialog1.ShowDialog();
}
C# Note   Be sure that the necessary code to wire up the event handler is present. In this case, it would be similar to the following:
//C#
this.button1.Click += new System.EventHandler(this.button1_Click);

Conclusion

The .NET Framework wraps many of the common dialogs encountered by Windows users, making it easy for you to include these familiar points of user interaction in your own applications. Often, there are a number of ways to complete a dialog's tasks; the .NET Framework leaves this aspect of the architecture open, so that you may code an approach that best suits the needs of your application. Above, we have covered some simple ways to accomplish the tasks associated with the dialog box components. This article provides some simple code that you can borrow or adapt to fit your own application.

Show:
© 2014 Microsoft