Getting to Know All of the Visual Basic Dialog Boxes

Introduction

What would life be without the little savvy gadgets that have become so essential in our existence as a species? Same rhetoric can be applied to Common dialog boxes in our programs. The majority of programs have at least one of the common dialogs present. It is something we cannot live without.

Imagine if MS Word, MS Excel, and MS PowerPoint had different Open boxes, or different Font boxes? It would have been chaos and learning to use Microsoft Office would have become much more difficult. Today, I will demonstrate how to use all of the .NET dialog boxes.

OpenFileDialog

Shown in Figure 1, the OpenFileDialog is the dialog that you will see any time you need to open a file. This dialog is quite customizable (as are all the other dialog boxes), because you can set the appropriate File Filters as well as what View you’d like this box to open in. More information regarding the OpenFileDialog can be found here.

Dialog1
Figure 1: OpenFileDialog

SaveFileDialog

The SaveFileDialog looks and behaves the same as the OpenFileDialog, except, it is used for saving files onto disk. Figure 2 shows this box in action. For more information regarding the SaveFileDialog, visit MSDN.

Dialog2
Figure 2: SaveFileDialog

FontDialog

The FontDialog allows you to select fonts as well as font styles for your text. An example of the FontDialogBox is shown in Figure 3. You can learn more about the FontDialog‘s settings here.

Dialog3
Figure 3: FontDialog

ColorDialog

With the ColorDialog, you are enabled to select a color for whichever object is in question. This dialog also has quite a few settings that you can use. For example, you can decide if you want to show Extended colors. More information on the ColorDialog can be found here.

Dialog4
Figure 4: ColorDialog

FolderBrowser Dialog

The FolderBrowserDialog enables you to select a folder. Figure 5 shows this dialog in action.

Dialog5
Figure 5: FolderBrowser

PageSetupDialog

As the name implies, the PageSetupDialog produces a dialog window in which you can set paper and page settings.

Dialog6
Figure 6: PageSetupDialog

PrintPreviewDialog

The PrintPreviewDialog Shows a preview of a document to be printed.

Dialog7
Figure 7: PrintPreviewDialog

Our Project

The aim of this project is to simply introduce you to the world of dialogs. Each dialog will have its own button dedicated to it, so it may seem as if there is no structure, and therefore I apologise.

Design

Open Visual Basic and create a new Windows Forms project. Add the following objects to your form:

  • 7 Buttons
  • 1 TextBox
  • 1 PictureBox
  • 1 ListBox
  • 1 OpenFileDialog
  • 1 SaveFileDialog
  • 1 FontDialog
  • 1 ColorDialog
  • 1 FolderBrowserDialog
  • 1 PageSetupDialog
  • 1 PrintPreviewDialog

Your design should resemble Figure 8:

Dialog8
Figure 8: Our Design

Code

Add the following code behind the button labelled ‘Open‘:

   Private Sub Button1_Click(sender As Object, e As EventArgs) _
      Handles Button1.Click

      OpenFileDialog1.Filter = "JPG Files|*.jpg"
      OpenFileDialog1.Title = "Select a JPEG File"

      If OpenFileDialog1.ShowDialog() = _
         System.Windows.Forms.DialogResult.OK Then

         PictureBox1.Image = _
            Image.FromFile(OpenFileDialog1.FileName)

      End If

   End Sub

The Filter gets set to accept only JPG files and the dialogbox’s title gets changed. Inside an IF statement, I determine whether the Open button was selected. If it was, it will show the image in the Picturebox.

Add the next code for the SaveFileDialog (Save):

   Private Sub Button2_Click(sender As Object, e As EventArgs) _
      Handles Button2.Click

      SaveFileDialog1.Filter = "JPeg Image|*.jpg|Bitmap Image| _
         *.bmp|Png Image|*.png"
      SaveFileDialog1.Title = "Save Picture"

      SaveFileDialog1.ShowDialog()

      If SaveFileDialog1.FileName <> "" Then

         Dim fsSave As System.IO.FileStream = CType _
            (SaveFileDialog1.OpenFile(), System.IO.FileStream)

         Select Case SaveFileDialog1.FilterIndex

            Case 1

               PictureBox1.Image.Save(fsSave, _
                  System.Drawing.Imaging.ImageFormat.Jpeg)

            Case 2

               PictureBox1.Image.Save(fsSave, _
                  System.Drawing.Imaging.ImageFormat.Bmp)

            Case 3

               PictureBox1.Image.Save(fsSave, _
                  System.Drawing.Imaging.ImageFormat.Png)

         End Select

         fsSave.Close()

      End If

   End Sub

In the preceding code, I have set a file filter again, this time allowing more than one type of file. If Save was pressed in the dialog as well as a filename filled in, the image in the Picturebox will get saved in the desired format, depending on the File filter that was selected.

Add the next code for the FontDialog:

   Private Sub Button3_Click(sender As Object, _
      e As EventArgs) Handles Button3.Click

      If FontDialog1.ShowDialog() <> _
         DialogResult.Cancel Then

         TextBox1.Font = FontDialog1.Font

      End If

   End Sub

This simply sets the font of the textbox to the selected font, if OK was selected.

Add the following code for the ColorDialog:

   Private Sub Button4_Click(sender As Object, _
      e As EventArgs) Handles Button4.Click

      If (ColorDialog1.ShowDialog() = _
         Windows.Forms.DialogResult.OK) Then

         TextBox1.ForeColor = ColorDialog1.Color

      End If

   End Sub

This sets the color of the TextBox’s text to the color chosen in the ColorDialog.

Add the following code for the FolderBrowserDialog:

   Private Sub Button5_Click(sender As Object, _
      e As EventArgs) Handles Button5.Click

      If FolderBrowserDialog1.ShowDialog() = _
         DialogResult.OK Then

         TextBox1.Text = FolderBrowserDialog1.SelectedPath

      End If

   End Sub

Again, only if OK was selected then something will happen—in this case, the path will be shown inside the Textbox.

Add the next code for the PageSetupDialog:

   Private Sub Button6_Click(sender As Object, _
      e As EventArgs) Handles Button6.Click

      PageSetupDialog1.PageSettings = New _
         System.Drawing.Printing.PageSettings

      PageSetupDialog1.PrinterSettings = New _
         System.Drawing.Printing.PrinterSettings

      Dim drResult As DialogResult = _
         PageSetupDialog1.ShowDialog()

      If (drResult = DialogResult.OK) Then

         Dim lstSettings() As Object = New Object() _
            {PageSetupDialog1.PageSettings.Margins, _
            PageSetupDialog1.PageSettings.PaperSize, _
            PageSetupDialog1.PrinterSettings.PrinterName}

         ListBox1.Items.AddRange(lstSettings)

      End If

   End Sub

All the settings chosen inside the PageSetupDialog will be shown inside the ListBox.

Finally, add the following code for the PrintpreviewDialog:

   Private strContents As String
   Private strPrint As String

   Private Sub ReadDoc()

      Dim strName As String = "tempdoc.txt" _
         ' file to print'
      Dim strPath As String = "c:\temp\"

      PrintDocument1.DocumentName = strName

      Dim fsFile As New FileStream(strPath + strName, _
         FileMode.Open)

      Try

         Dim reader As New StreamReader(fsFile)

         Try

            strContents = reader.ReadToEnd()

         Finally

            reader.Dispose()

         End Try

      Finally

         fsFile.Dispose()

      End Try

      strPrint = strContents

   End Sub

   Private Sub Button7_Click(sender As Object, _
      e As EventArgs) Handles Button7.Click

      ReadDoc()
      PrintPreviewDialog1.Document = PrintDocument1
      PrintPreviewDialog1.ShowDialog()

   End Sub

   Private Sub PrintDocument1_PrintPage(sender As Object, _
      e As Printing.PrintPageEventArgs) Handles _
      PrintDocument1.PrintPage

      Dim intChars As Integer = 0
      Dim intLines As Integer = 0

      e.Graphics.MeasureString(strPrint, Me.Font, _
         e.MarginBounds.Size, StringFormat.GenericTypographic, _
         intChars, intLines)

      e.Graphics.DrawString(strPrint, Me.Font, Brushes.Black, _
         e.MarginBounds, StringFormat.GenericTypographic)

      strPrint = strPrint.Substring(intChars)

      e.HasMorePages = strPrint.Length > 0

      If Not e.HasMorePages Then

         strPrint = strContents

      End If

   End Sub

This one works a bit more differently…

Because you have to show a preview of the document, you should obviously have some logic to open the document and show the document’s text inside the PrintPreviewDialog window.

The Sub procedure ReadDoc opens a document named tempdoc.txt which is found in the C:\temp folder on my hard disk. The StreamReader then reads each line in the document and adds it to the preview window. The preview window makes use of the Graphics.DrawString methods to draw the contents of the file into a pictureformat so that it can be displayed in the Preview window as well as printed proportionally.

Conclusion

CommonDialogs will very quickly become your best friends. As you can see, they are not at all difficult to implement.

Hannes DuPreez
Hannes DuPreez
Ockert J. du Preez is a passionate coder and always willing to learn. He has written hundreds of developer articles over the years detailing his programming quests and adventures. He has written the following books: Visual Studio 2019 In-Depth (BpB Publications) JavaScript for Gurus (BpB Publications) He was the Technical Editor for Professional C++, 5th Edition (Wiley) He was a Microsoft Most Valuable Professional for .NET (2008–2017).

More by Author

Get the Free Newsletter!

Subscribe to Developer Insider for top news, trends & analysis

Must Read