Home

Accessories for File Processing

 

Documents

 

Introduction

When creating an application, if it is a word processor, after opening the application, it may display an empty area in which the user can start typing. If the user is working on a spreadsheet, he or she may start typing numbers and performing calculations. In the same way, a user who is facing a graphics application would start drawing in it. The object that a user would be using is called a document. After working on a document for a while, there are some other automatic ideas that come in the mind of a user. One would lead to saving the document. Another would consist of printing it. All these routine operations should be available to the user. This aspect of the application is taken care of by the person who creates the application. Not every application allows a user to save or to print its documents. If you want these operations to be possible, you must (explicitly) provide them.

 

Windows Common Dialog Boxes

To support the various operations of saving a document, opening an existing document, printing a document, setting up printing, etc, Microsoft Windows provides a series of standard dialog boxes that are available almost regardless of the programming environment you are using to develop your application. These common dialog boxes are stored in libraries (DLLs) that ship with the operating system but they may be provided in a raw format. For this reason, except if programming in Win32, the programming environment you use provides a customized and friendlier technique of adding these dialog boxes to your application. In the same way, the .NET Framework provides its own implementation of these ready-made dialog boxes in a manner that makes it easier to implement them.

To use a standard Windows dialog box, from the Toolbox, click the button that corresponds to the dialog box you want to add and click the form anywhere. The position of the control on the form has no importance because it is only a representative: it will not appear when the form is running. Once the desired dialog’s icon is on the form, place a button on the form or create a menu item that will be used to call the dialog box.

Introduction to the Save As Dialog Box

 

Description

Most of the applications allow users to open or display an empty document. This indicates that such an application expects the user to create a document. Once a document has been created, a user would usually want to store its contents on a medium (hard drive, floppy disk, etc). Microsoft Windows provides a common dialog box for this purpose: The Save As dialog box:

The Save As Dialog Box

The primary role of the Save As dialog box is to allow users to store a file on the hard drive of the computer, on a portable medium such as a floppy disk, or on a network drive. To make this efficient and complete, the user must supply two valuable pieces of information: the location and the name of the file. The location of a file is also known as its path.

The name of a file follows the directives of the operating system. On MS DOS and Windows 3.X, it had to be in an 8.3 format. The actual name had to have a maximum of 8 characters with restrictions on the characters that could be used. The user also had to specify three characters after a period. The three characters, known as the file extension, were used by the operating system to classify the file. That was all necessary for those 8-bit and 16-bit operating systems.

Various rules have changed. For example, the names of folders and files on Microsoft Windows >= 95 can have up to 255 characters. The extension of the file is mostly left to the judgment of the programmer but most files are still using extensions. Applications can also be configured to save different types of files; that is, files with different extensions.

To use the Save As dialog box, users usually click an item under the File menu. Here is how it works for most regular applications. The user creates a new document. If the user wants to save the file, he or she can click File -> Save. If the document was not previously saved, the application would call the Save As dialog box. If a document is displaying, whether it was saved previously or not, the user can also click File -> Save As... which also would call the Save As dialog box.

Two objects are particularly important on the Save As dialog box: The Save In combo box and the File Name text box or combo box (the File Name box is made of a combo box to make it user-friendly but over all, users hardly use the list side of this combo box). Since Windows 95, the user does not have to specify an extension if the programmer makes it easy. To help with this, the Save As dialog box is equipped with a Save As Type combo box. This combo box allows the user to select one of the extensions. The available extensions have to be created by the programmer so the user can select from a preset list. If the programmer neglects this, the user would have no extension to select from. Although the file can still be saved, the operating system would not associate it with a known type of file. Therefore, if you specify a series of extensions, the user can select one of these and, in the File Name box, he or she can simply type a name for the file.

If the user does not specify an extension, the operating system would associate the extension of the Save As Type combo box. Users of regular commercial applications, such as word processors, spreadsheet programs, or graphical applications, etc, are usually trained not to care about the extensions and let the application deal with that detail. In some other circumstances, the users must pay close attention to the extension they give a file. This is common on web development or graphics design because various file extensions are supported and overall produce the same end result.

After working on a Save As dialog box, users can click Save or press Enter, which would validate their entry. To change their mind, regardless of what they did on the Save As dialog box, users can click Cancel or press Esc, which would dismiss the dialog box and ignore what they did (in reality, some actions cannot be ignored, such as creating a new file or folder inside of the Save As dialog box, deleting, cutting, or pasting files, etc; but if the user clicked Cancel or pressed Esc, the new file would not be saved).

Save As Dialog Box Creation

To make a Save As dialog box available to your application, on the Toolbox, you can click the SaveFileDialog button SaveFileDialog Control and click the form. To programmatically provide this dialog box, you can declare a SaveFileDialog variable and initialize it using the class's default constructor as follows:

using System;
using System.Windows.Forms;

public class Exercise : Form
{
    private SaveFileDialog sfd;

    public Exercise()
    {
	InitializeComponent();
    }

    void InitializeComponent()
    {
        sfd = new SaveFileDialog();
    }
}

public class Program
{
    public static int Main()
    {
        Application.Run(new Exercise());

        return 0;
    }
}

The SaveFileDialog class inherits from the FileDialog class from which it gets most of its characteristics and behaviors.

Characteristics of the Save As Dialog Box

 

The File Extension

To make sure that your application can open the allowed types of files, depending on your goals, you should create a list of extensions that you want the users to be able to open. The allowed extensions form a group called a filter. The filter is like a funnel that selects the good items. For a text-based application, you may allow only text files, that is, files with a txt extension. For a rich text-based application, you may allow only Rich Text Format files, which are files with rtf extension. On the other hand, if you are creating an application for web files, you can allow as many file extensions as necessary, such as htm, html, php, asp, etc. As you may realize, text files or web files are all text-based files. This means that if you create a text-based or rich-text based application, you should allow the users to decide whether the file they are trying to open can be "read" by a text-based control. To provide this ability, you can specify an unknown extension specified as All Files.

The Filter

To create a list of allowable extensions for your FileSaveDialog object, you can use the Filter property from the Properties window. At run time, you can create a list of file extensions as a string. If the Save As dialog box will need only one extension, you can create the string using the following syntax:

Prompt|Extension

The Prompt is a section that defines what the user would see in the Save As Type combo box. An example would be 24-bit Bitmap. Such a string does not let the user know what actual extension the file would use. Therefore, as a courtesy, you can specify, between parentheses, the extension that would be applied if this extension is used. The Prompt can be 24-bit Bitmap (*.bmp). In this case, the extension used would be bmp. The asterisk * lets the user know that whatever is provided as the file name would be used in place of the asterisk. The period indicates the separation from the file to its extension. This means that the characters on the left of the period would be the file name, the characters on the right side of the period would be used as the actual file extension.

To specify the extension that the operating system would use to associate to the file, you provide a second part of the string as Extension. In Microsoft Windows, most extensions are made of three characters. Some applications use a 2-letter extensions (for example Perl files have a pl extension) and some others use 4 letters (such as html for some HTML files). This depends on the programmer (or the company that is publishing the application). An example of a string as an extension is:

24-bit Bitmap (*.bmp)|*.bmp

If you want to provide various extensions to your Save As dialog box, you can separate them with a | symbol. An example would be:

HTML Files (*.htm)|*.htm|Active Server Pages (*.asp)|*.asp|Perl Script (*.pl)|*.pl

If you added a FileSaveDialog control to a form, as mentioned earlier, you can type the filter string in the Filter field of the Properties window. If your programmatically creating the dialog box, you can assign the string to the Filter property. Here is an example:

public class Exercise : Form
{
    private SaveFileDialog sfd;

    public Exercise()
    {
	InitializeComponent();
    }

    void InitializeComponent()
    {
        	sfd = new SaveFileDialog();
	sfd.Filter = "HTML Files (*.htm)|*.htm|" +
                                  "Active Server Pages (*.asp)|*.asp|" +
                                  "Apache Files (*.php)|*.php|" +
                                  "Perl Script (*.pl)|*.pl|" +
                                  "All Files|";
    }
}

This would produce:

The Save As dialog box with various file extensions

The Filter Index

A filter organizes its extensions and categories as indexes. The above filter has the following indexes:

Index 1 = HTML Files (*.htm)
Index 2 = Active Server Pages (*.asp)
Index 3 = Apache Files (*.php)
Index 4 = Perl Script (*.pl)
Index 5 = All Files;

After creating a filter, when the dialog box comes up, the Save As Type combo box displays the first index of the filter. If you want, instead of displaying the first index by default, you can specify another index. To specify the desired index at design time, change the value of the FilterIndex field in the Properties window. To programmatically specify it, assign a value to the FileSaveDialog.FilterIndex property. Here is an example:

public class Exercise : Form
{
        private SaveFileDialog sfd;

        public Exercise()
        {
	InitializeComponent();
        }

        void InitializeComponent()
        {
        	sfd = new SaveFileDialog();
	sfd.Filter = "HTML Files (*.htm)|*.htm|" +
                                  "Active Server Pages (*.asp)|*.asp|" +
                                  "Apache Files (*.php)|*.php|" +
                                  "Perl Script (*.pl)|*.pl|" +
                                  "All Files|";
    	sfd.FilterIndex = 3;
        }
}

Once you know the types of files that your application will be dealing with, you can make your dialog box friendly by displaying the most likely extension for a document created using your application. For example, if you create a text-based application, users are more likely to create a text file with it. If you create a rich text-based application, users are more likely to create a Rich Text Format file with it. This most likely extension is known as the default extension, it allows the user not to provide an extension in the most likely cases when saving a file. By simply providing a file name and clicking Save, the operating system would associate the file with the default extension. Of course, if you create a filter, the user can specify a desired allowed extension.

The Default Extension

To specify the default extension for your FileSaveDialog object, type the desired extension in the DefaultExt field of the Properties window. If you had created a Filter and if you provide a default extension for a FileSaveDialog object, make sure it is one of the file extensions specified in the Filter list. To programmatically specify a default extension, assign it to the DefaultExt property of your FileSaveDialog variable. Here is an example:

public class Exercise : Form
{
    private SaveFileDialog sfd;

    public Exercise()
    {
	InitializeComponent();
    }

    void InitializeComponent()
    {
        	sfd = new SaveFileDialog();
	sfd.Filter = "HTML Files (*.htm)|*.htm|" +
                                  "Active Server Pages (*.asp)|*.asp|" +
                                  "Apache Files (*.php)|*.php|" +
                                  "Perl Script (*.pl)|*.pl|" +
                                  "All Files|";
    	sfd.FilterIndex = 3;
    	sfd.DefaultExt = "htm";
    }
}

Displaying the Dialog Box

Once the OpenFileDialog object is ready, to display it to the user, call its ShowDialog() method. Here is an example:

using System;
using System.Windows.Forms;

public class Exercise : Form
{
    private SaveFileDialog sfd;

    public Exercise()
    {
	InitializeComponent();
    }

    void InitializeComponent()
    {
        sfd = new SaveFileDialog();
        sfd.Filter = "HTML Files (*.htm)|*.htm|" +
                                  "Active Server Pages (*.asp)|*.asp|" +
                                  "Apache Files (*.php)|*.php|" +
                                  "Perl Script (*.pl)|*.pl|" +
                                  "All Files|";
        sfd.FilterIndex = 3;
        sfd.DefaultExt = "htm";

        sfd.ShowDialog();
    }
}

public class Program
{
    public static int Main()
    {
        Application.Run(new Exercise());

        return 0;
    }
}

Microsoft Windows operating systems, especially since Windows 9X, are configured to have a default folder in which users are most likely to save their files. On Windows 9X, it is C:\My Documents. On Windows NT, it is usually specified by the network administrator. On Windows 2000 and Windows XP, it uses a more customized scenario. These settings are known to the operating system and you will usually not be concerned with them. In some circumstances, if you want to specify the folder in which the users should save their files by default, you can provide it using the InitialDirectory property. This directory usually ends with \My Documents. If you want to find the path to the My Documents for a user, you can call the Environment.GetFolderPath() method and pass it the Personal member of the Environment.SpecialFolder enumerator. The syntax of the GetFolderPath() method is:

public static string GetFolderPath(SpecialFolder folder);

Here is an example:

private System.Void button1_Click(System.Object    sender, System.EventArgs    e)
{
    string  strMyDocuments = 
	Environment.GetFolderPath(Environment.SpecialFolder.Personal);
    this.textBox1.Text = strMyDocuments;
}

Once again, most of the time, you will not be concerned with this issue if you are creating an application for any user.

Probably the most important issue users care about, as far as they are concerned, is a name for the file they are trying to save. Users know that they can set the name of the file in the File Name box. To make this action a little faster, you can provide a default name for a file in case a user does not want to specify a file name. This is done by typing a name in the FileName field of the Properties window. In practicality, the FileName value is the string that displays in the File Name box of the Save As dialog box.

By default, when the Save As dialog box comes up, it displays "Save As" on its title bar. If you want a different caption, set the desired string in the Title field of the Properties window or assign a string to the FileSaveDialog.Title property.

Introduction to the Open File Dialog Box

 

Description

Besides saving files, another common operation performed by users consists of opening files. This refers to existing files since a file must primarily exist. To support this operation, Microsoft Windows provides a standard object: the Open File dialog box:

Description of the Open File Dialog Box
  

Practical LearningPractical Learning: Introduction the Open File Dialog Box

  1. Start a new Windows Forms Application named PictureViewer2
  2. Change the properties of the form as follows:
    Text: Picture Viewer
    StartPosition: CenterScreen
  3. On the main menu, click Project -> Add New Item...
  4. In the Add New Item dialog box, click Icon File
  5. Set the Name to openpicture and click Add
  6. Right-click the picture and click Delete Image Type
  7. Design the 16x16 icon as follows:
     
  8. On the main menu, click File -> Save openpicture.ico As...
  9. Select the PictureViewer2\PictureViewer2\bin\Debug folder
  10. Click Save
  11. In the Solution Explorer, expand the bin\Debug folder. Right-click the Debug folder -> Add -> New Item...
  12. Select Icon File. Set the Name to f the project -> Add -> Resource...
  13. In the Add Resource dialog box, double-click Icon flip and click Add
  14. Right-click the picture and click Delete Image Type
  15. Design the 16x16 icon as follows:
     
    Flip
  16. Save and close the icon design
  17. In the Solution Explorer, right-click the Debug folder -> Add -> New Item...
  18. Select Icon File. Set the Name to mirror.ico and click Add
  19. Right-click the picture and click Delete Image Type
  20. Design the 16x16 icon as follows:
     
    Mirror
  21. Save and close the icon design
  22. In the Solution Explorer, right-click the Debug folder -> Add -> New Item...
  23. Select Icon File. Set the Name to rotate90right and click Add
  24. Right-click the picture and click Delete Image Type
  25. Design the 16x16 icon as follows:
     
    IDI_ROTATE90RIGHT
  26. Save and close the icon design
  27. In the Solution Explorer, right-click the Debug folder -> Add -> New Item...
  28. Select Icon File. Set the Name to rotate90left and click Add
  29. Right-click the picture and click Delete Image Type
  30. Design the 16x16 icon as follows:
     
    IDI_ROTATE90LEFT
  31. Save and close the icon design
  32. In the Solution Explorer, right-click the Debug folder -> Add -> New Item...
  33. Select Icon File. Set the Name to rotate180 and click Add
  34. Right-click the picture and click Delete Image Type
  35. Design the 16x16 icon as follows:
     
    IDI_ROTATE180
  36. Save and close the icon design
  37. In the Solution Explorer, right-click the Debug folder -> Add -> New Item...
  38. Select Icon File. Set the Name to fliprotate90right and click Add
  39. Right-click the picture and click Delete Image Type
  40. Design the 16x16 icon as follows:
     
    IDI_FLIPROTATE90RIGHT
  41. Save and close the icon design
  42. In the Solution Explorer, right-click the Debug folder -> Add -> New Item...
  43. Select Icon File. Set the Name to fliprotate90left and click Add
  44. Right-click the picture and click Delete Image Type
  45. Design the 16x16 icon as follows:
     
  46. Save and close the icon design
  47. In the Solution Explorer, right-click the Debug folder -> Add -> New Item...
  48. Select Icon File. Set the Name to fliprotate180 and click Add
  49. Right-click the picture and click Delete Image Type
  50. Design the 16x16 icon as follows:
     
    IDI_FLIPROTATE180
  51. Save and close the icon design
  52. From the Menus & Toolbars section of the Toolbox, click MenuStrip and click the form
  53. While the menu strip is still selected under the form, in the Properties window, click (Name) and type mnuMain
  54. Use the menu designer and/or the Items field of the Properties window to create the menu items as follows:
     
    Menu Top Sub Items/DropDownItems
    Text Name Text Name Image
    &File mnuFile &Open Picture... mnuFileOpenPicture openpicture.ico
        Separator    
        E&xit mnuFileExit  
     
    Picture Viewer
     
    Menu Top Sub Items/DropDownItems
    Text Name Text Name Image
    &Tools mnuTools &Flip mnuToolsFlip flip.ico
        &Mirror mnuToolsMirror mirror.ico
        Separator    
        &Rotate mnuToolsRotate  
        Flip && R&otate mnuToolsFlipRotate  
     
    Picture Viewer
     
     
    Sub Item Sub Items/DropDownItems
    Text Text Name Image
    Rotate 90º mnuToolsRotate90  
      180º mnuToolsRotate180 rotate180.ico
    Flip & Rotate 90º mnuToolsFlipRotate90  
      180º mnuToolsFlipRotate180 fliprotate180.ico
    Picture Viewer
     
    Picture Viewer
     
    Sub Item Sub Item Sub Items/DropDownItems
    Text Text Text Name Image
    Rotate 90º &Left mnuToolsRotate90Left rotate90left.ico
        &Right mnuToolsRotate90Right rotate90right.ico
    Flip & Rotate 90º &Left mnuToolsFlipRotate90Left fliprotate90left.ico
        &Right mnuToolsFlipRotate90Right fliprotate90right.ico
     

     
     
    Menu Top Sub Item
    Text Text Name
    &Tools Flip & Rotate  
      Separator  
      &Original Size mnuOriginalSize
      Ce&nter Image mnuCenterImage
      R&esize Form to Fit Picture mnuResizeForm
      O&ccupy Client Area mnuOccupyClientArea
      &Zoom mnuZoom
    Picture Viewer
  55. From the Common Controls section of the Toolbox, click PictureBox and click the form
  56. In the Properties window, change its characteristics as follows:
    BorderStyle: Fixed3D
    (Name): pbxViewer
    Dock: Fill 
  57. You can copy the following pictures and add them to a folder on your computer (for example the PictureViewer2\PictureViewer2\bin\Debug folder of the current project)
     
    Click to open Click to open
  58. In the Solution Explorer, right-click Form1.cs and click Rename
  59. Type PictureViewer.cs and press Enter twice
  60. Right-click the form and click View Code
  61. Declare a private Bitmap variable named bmpPicture
     
    namespace PictureViewer2
    {
        public partial class Form1 : Form
        {
            Bitmap bmpPicture;
    
            public Form1()
            {
                InitializeComponent();
            }
        }
    }
  62. Return to the form
  63. On top of the Properties window, click the arrow of the combo box and select PictureViewer
  64. Click the Events button Events and double-click Paint
  65. Implement the event as follows:
     
    private void PictureViewer_Paint(object sender, PaintEventArgs e)
    {
            if( bmpPicture != null )
            {
                    pbxViewer.Image = bmpPicture;
            }
    }
  66. Return to the form
  67. Click Tools and double-click Flip
  68. Implement the event as follows:
     
    private void mnuToolsFlip_Click(object sender, EventArgs e)
    {
            if( bmpPicture != null )
            {
                    bmpPicture.RotateFlip(RotateFlipType.RotateNoneFlipY);
                    Invalidate();
            }
    }
  69. Return to the form, click Tools and double-click Mirror
  70. Implement the event as follows:
     
    private void mnuToolsMirror_Click(object sender, EventArgs e)
    {
            if (bmpPicture != null)
            {
                    bmpPicture.RotateFlip(RotateFlipType.RotateNoneFlipX);
                    Invalidate();
            }
    }
  71. Return to the form, click Tools, then click Rotate, then click 90º and double-click Left
  72. Implement the event as follows:
     
    private void mnuToolsRotate90Left_Click(object sender, EventArgs e)
    {
            if (bmpPicture != null)
            {
                    bmpPicture.RotateFlip(RotateFlipType.Rotate270FlipNone);
                    Invalidate();
            }
    }
  73. Return to the form, click Tools, then click Rotate, then click 90º and double-click Right
  74. Implement the event as follows:
     
    private void mnuToolsRotate90Right_Click(object sender, EventArgs e)
    {
            if (bmpPicture != null)
            {
                    bmpPicture.RotateFlip(RotateFlipType.Rotate90FlipNone);
                    Invalidate();
            }
    }
  75. Return to the form, click Tools, then click Rotate, and double-click 180º
  76. Implement the event as follows:
     
    private void mnuToolsRotate180_Click(object sender, EventArgs e)
    {
            if (bmpPicture != null)
            {
                    bmpPicture.RotateFlip(RotateFlipType.Rotate180FlipNone);
                    Invalidate();
            }
    }
  77. Return to the form, click Tools, then click Flip & Rotate, then click 90º and double-click Left
  78. Implement the event as follows:
     
    private void mnuToolsFlipRotate90Left_Click(object sender, EventArgs e)
    {
            if (bmpPicture != null)
            {
                    bmpPicture.RotateFlip(RotateFlipType.Rotate270FlipX);
                    Invalidate();
            }
    }
  79. Return to the form, click Tools, then click Flip & Rotate, then click 90º and double-click Right
  80. Implement the event as follows:
     
    private void mnuToolsFlipRotate90Right_Click(object sender, EventArgs e)
    {
            if (bmpPicture != null)
            {
                    bmpPicture.RotateFlip(RotateFlipType.Rotate90FlipX);
                    Invalidate();
            }
    }
  81. Return to the form, click Tools, then click Flip & Rotate, and double-click 180º
  82. Implement the event as follows:
     
    private void mnuToolsFlipRotate180_Click(object sender, EventArgs e)
    {
            if (bmpPicture != null)
            {
                    bmpPicture.RotateFlip(RotateFlipType.Rotate180FlipX);
                    Invalidate();
            }
    }
  83. Return to the form, click Tools and double-click Original Size
  84. Implement its event as follows:
     
    private void mnuToolsOriginalSize_Click(object sender, EventArgs e)
    {
            if (bmpPicture != null)
            {
                    pbxViewer.SizeMode = PictureBoxSizeMode.Normal;
    
                    mnuOriginalSize.Checked = true;
                    mnuCenterImage.Checked = false;
                    mnuOccupyClientArea.Checked = false;
                    mnuZoom.Checked = false;
            }
    }
  85. Return to the form, click Tools and double-click Center Image
  86. Implement its event as follows:
     
    private void mnuToolsCenterImage_Click(object sender, EventArgs e)
    {
            if (bmpPicture != null)
            {
                    pbxViewer.SizeMode = PictureBoxSizeMode.CenterImage;
    
                    mnuOriginalSize.Checked = false;
                    mnuCenterImage.Checked = true;
                    mnuOccupyClientArea.Checked = false;
                    mnuZoom.Checked = false;
            }
    }
  87. Return to the form, click Tools and double-click Occupy Client Area
  88. Implement its event as follows:
     
    private void mnuOccupyClientArea_Click(object sender, EventArgs e)
    {
            if (bmpPicture != null)
            {
                    pbxViewer.SizeMode = PictureBoxSizeMode.StretchImage;
    
                    mnuOriginalSize.Checked = false;
                    mnuCenterImage.Checked = false;
                    mnuOccupyClientArea.Checked = true;
                    mnuZoom.Checked = false;
            }
    }
  89. Return to the form, click Tools and double-click Zoom
  90. Implement its event as follows:
     
    private void mnuZoom_Click(object sender, EventArgs e)
    {
            if (bmpPicture != null)
            {
                    pbxViewer.SizeMode = PictureBoxSizeMode.Zoom;
    
                    mnuOriginalSize.Checked = false;
                    mnuCenterImage.Checked = false;
                    mnuOccupyClientArea.Checked = false;
                    mnuZoom.Checked = true;
            }
    }
  91. Return to the form

Open File Dialog Box Creation

To provide file opening support, the .NET Framework provides the OpenFileDialog class which is derived from the FileDialog class that in fact provides most of its functionality. The easiest way to use it is to click the OpenFileDialog button OpenFileDialog from the Toolbox and click the form. You can click anywhere on the form because the OpenFileDialog object would not be seen at run time. After placing it on the form, you can use the Properties window to configure it.

If you prefer to dynamically create an Open dialog box, declare a variable of type OpenFileDialog and use the new operator to allocate memory using its default constructor. Here is an example:

using System;
using System.Windows.Forms;

public class Exercise : Form
{
    private OpenFileDialog  ofd;

    public Exercise()
    {
	InitializeComponent();
    }

    void InitializeComponent()
    {
        ofd = new OpenFileDialog();
    }
}

public class Program
{
    public static int Main()
    {
        Application.Run(new Exercise());

        return 0;
    }
}

Practical LearningPractical Learning: Enabling or Disabling Menu Items

  1. From the Dialogs section of the Toolbox, click OpenFileDialog OpenFileDialog and click the form
  2. While the open file control is still selected under the form, in the Properties window, click (Name) and type ofdPicture

Characteristics of an Open File Dialog Box

 

The Filename

One of the most important properties of an Open dialog box is the file it presents to the user. This is represented by the FileName property. If you want a default file to be specified when the dialog box comes up, you can specify this in the FileName property of the Properties window. If you need to use this property, you should make sure the file can be found. If the file is located in the same folder as the application, you can provide just its name. If the file is located somewhere else in the hard drive, you should provide its complete path. Most of the time, you will not be concerned with this property if you are creating an application that will allow the users to open any files of their choice. Once a file is located, it can be accessed using the OpenFileDialog.FileName property.

Practical LearningPractical Learning: Using the File Name

  • Still in the Properties window for the open file control, click FileName and delete its string

The Filter

To make your application more effective, you should know what types of files your application can open. This is taken care of by specifying a list of extensions for the application. To control the types of files that your application can open, specify their extensions using the Filter Property. The Filter string is created exactly like that of a SaveFileDialog control as we saw earlier.

Practical LearningPractical Learning: Filtering Files

  1. Still in the Properties window for the open file control, click Filter and type:
    Bitmap Files (*.bmp)|*.bmp|JPEG Files (*.jpg,*.jpeg)|*.jpg|GIF Files (*.gif)|*.gif|PNG Files (*.png)|*.png
  2. Save the form

The Filter Index

Like the SaveFileDialog control, the default extension is the one the dialog box would first filter during file opening. If you want the Open dialog box to easily recognize a default type of file when the dialog box opens, you can specify the extension's type using the DefaultExt property. You can also use the FilterIndex we saw earlier to indicate the default index of the Files of Type combo box.

For convenience, or for security reasons, Open dialog boxes of applications are sometimes asked to first look for files in a specific location when the Open File dialog box comes up. This default folder is specified using the InitialDirectory property.

Practical LearningPractical Learning: Specifying the Default Extension

  1. Still in the Properties window for the open file control, click DefaultExt and type bmp
  2. Save the form

Showing the Dialog Box

The essence of using the Open dialog box is to be able to open a file. This job is handled by the ShowDialog() method. Here is an example:

public class Exercise : Form
{
    private OpenFileDialog  ofd;

    public Exercise()
    {
	InitializeComponent();
    }

    void InitializeComponent()
    {
        ofd = new OpenFileDialog();
        ofd.ShowDialog();
    }
}

After opening the dialog box, if the user selects a file and clicks OK or presses Enter, the file would be opened.

Practical LearningPractical Learning: Using the Open File Dialog Box

  1. On the form, click File and double-click Open Picture
  2. Implement the event as follows:
     
    private void mnuFileOpenPicture_Click(object sender, EventArgs e)
    {
            if (ofdPicture.ShowDialog() == DialogResult.OK)
            {
                    bmpPicture = new Bitmap(ofdPicture.FileName);
                    Invalidate();
                    mnuToolsOriginalSize_Click(sender, e);
            }
    }
  3. Return to the form
  4. Click Tools and double-click Exit
  5. Implement the event as follows:
     
    private void mnuFileExit_Click(object sender, EventArgs e)
    {
            Close();
    }
  6. Execute the application
  7. Open a picture and use the menu items
     
  8. Close the form and return to your programming environment

Opening Various Files

Most of the time, users are interested in opening one file to view or manipulate. It is also possible for a user to want to select various files and open them at the same time. When the user clicks OK after using the Open dialog box, before taking the next step, you may need to find out whether the user selected various files. To get this information, you can check the value of the OpenFileDialog.Multiselect Boolean property. If the user had selected various files, this property produces a true result. If the user selected only one file, this property renders a false result. The result of this checking process allows you either to agree to open the files or to take some action of your choice.

Opening a File As Read-Only

After a file has been opened, the user may want to alter it. For example, if it is a text document, the user may want to add and/or delete some words. In some cases, you may want the user to be able to open a file but not to be able to modify it. To provide this restriction, you can set the document as read-only. In some other cases, you may want to let the user decide on this. If you want to give this option to the user, you can start by displaying a read-only check box on the dialog box. To support this, the OpenFileDialog class is equipped with the ShowReadOnly property. If you set it to true, the dialog box would be equipped with an Open As Read-Only check box in its lower section:

Open

By default, the Open As Read-Only check box is cleared when the dialog box comes up. The user has the option of keeping it that way or checking it when opening a file. The OpenFileDialog class provides the ReadOnlyChecked property to accompany the read-only option. If you want to display a check mark in the Open As Read-Only check box, you can set the ReadOnlyChecked property to true. On the other hand, when the user selects a file to open, you can check the value of the ReadOnlyChecked property. If it is true, this indicates that the user had clicked the Open As Read-Only check box.

Introduction to the Browse For Folder Dialog Box

 

Description

The Save and Open dialog boxes allow a user to save or open files only. Microsoft Windows provides a dialog box specially made so that a user can select a folder if an application needs one for any reason a programmers judges necessary. This dialog box appears as follows:

The Browse For Folder Dialog Box

When this dialog box comes up, it displays the Desktop folder as the parent and all the other folders can be located from it. To use it, the user can click one of the folders or drives and click OK. If the desired folder is not seen but is available, the user can expand the existing folders and drives, click the desired folder, and click OK. If the necessary folder is not available at all, the user can first select an existing folder or drive, click the Make New Folder button, type a name for the new folder, and click OK.

Besides the folders, the Browse For Folder dialog box also allows the user to navigate to folders or directories of the network.

Creating a Browse For Folder Dialog Box

The Browse For Folder dialog box is made available through the FolderBrowserDialog class that is derived from the CommonDialog class. To provide its functionality to your application, at design time, from the Toolbox, click FolderBrowserDialog FolderBrowserDialog and click the form.

To programmatically initiate this dialog box, you can declare a pointer to FolderBrowserDialog, use the new operator to allocate memory for it by calling its default constructor.

To display the Browse For Folder dialog box, call its ShowDialog() method. Here is an example:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace WindowsApplication2
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void label1_Click(object sender, EventArgs e)
        {
            folderBrowserDialog1.ShowDialog();
        }
    }
}

This would produce:

Characteristics of the Browse For Folder Dialog Box

 

The Description

By default, and as seen on the above screenshot, the Browse For Folder dialog box doesn't indicate what it is used for. This is because it is left to you to let the user know what you expect. To provide this information, the Browse For Folder dialog box is equipped with a label that can be made visible or not. It is available through the Description property. If you provide a string for this property, it would display under the title bar but above the tree view of the dialog box. If you add the FolderBrowserDialog FolderBrowserDialog control to the form, you can type a string in the Description field in the Properties window. You can also programmatically assign a string to the FolderBrowserDialog object. Here is an example:

public partial class Form1 : Form
{
        public Form1()
        {
            InitializeComponent();
        }

        private void label1_Click(object sender, EventArgs e)
        {
            folderBrowserDialog1.Description =
                "Select the directory where your " +
		"future configurations will be installed";
            folderBrowserDialog1.ShowDialog();
        }
}

This would produce:

The Browse For Folder dialog box with an indicative label

The Root Folder

As you can see from this screenshot, when the dialog box comes up, it selects the Desktop, by default, as the parent folder. If you want, you can specify a different default folder to be selected. This information is carried by the RootFolder property. The RootFolder value must be a member of the SpecialFolder enumerator of the Environment class. For example, to select My Documents, you would type the following:

public partial class Form1 : Form
{
        public Form1()
        {
            InitializeComponent();
        }

        private void label1_Click(object sender, EventArgs e)
        {
            folderBrowserDialog1.Description =
                "Select the directory where your " +
		"future configurations will be installed";
            folderBrowserDialog1.RootFolder = Environment.SpecialFolder.Personal;
            folderBrowserDialog1.ShowDialog();
        }
}

This would produce:

The Selected Path

Since there is only a limited number of folders of the SpecialFolder enumerator, you may want to specify a different folder. The advantage of the SpecialFolder option is that it is likely to be found on the user's computer. If you know for sure that a certain folder exists on the computer and you would rather select that folder, you can provide its complete path to the SelectedPath property. Here is an example:

public partial class Form1 : Form
{
        public Form1()
        {
            InitializeComponent();
        }

        private void label1_Click(object sender, EventArgs e)
        {
            folderBrowserDialog1.Description =
                "Select the directory where your " +
		"future configurations will be installed";
            folderBrowserDialog1.SelectedPath = @"C:\Programs\Corporate";
            folderBrowserDialog1.ShowDialog();
        }
}

This would produce;

Browse For Folder

You should not specify both the RootFolder and the SelectedPath properties on the same FolderBrowserDialog control.

After the user has used the Browse For Folder dialog box, has selected a folder, and clicked OK, to find out what folder the user selected, get the value of the SelectedPath property.

The Make New Folder Button

After using the Browse For Folder dialog box, the user may select a folder and click OK. Imagine you are creating a commercial application, you can't possibly know the content of every customer's computer. This means that there is a possibility that the user would not find the desired folder. One solution you can use is to give users the ability to create a new folder. This option is available by default. If you want to prevent the user from creating a new folder, hide the Make New Folder button. To do this, assign a false value to the ShowNewFolderButton Boolean property. You can do this in the Properties window at design time or programmatically as follows:

public partial class Form1 : Form
{
        public Form1()
        {
            InitializeComponent();
        }

        private void label1_Click(object sender, EventArgs e)
        {
            folderBrowserDialog1.Description =
                "Select the directory where your " +
		"future configurations will be installed";
            folderBrowserDialog1.SelectedPath = @"C:\Programs\Corporate";
            folderBrowserDialog1.ShowNewFolderButton = false;
            folderBrowserDialog1.ShowDialog();
        }
}

This would produce:

The Browse For Folder dialog box without the Make New Folder button

You can also check the value of the ShowNewFolderButton property to find out whether the dialog box is equipped with a Make New Folder button.

 
 

Previous Copyright © 2008-2009, yevol.com Next