1. Technology
Send to a Friend via Email

OPEN AND SAVE - CREATING NOTEPAD
Working with common dialog boxes: Open and Save.
How to create my own Notepad using Delphi. Part 1.

   The Common Dialog Boxes
While working with various Windows applications and Delphi, we've become accustomed to operating with one of the standard dialog boxes for opening and saving a file, finding and replacing text, printing, choosing fonts or setting colors.
In this article, we'll examine some of the most important properties and methods of those dialogs with a special focus to Open and Save dialog boxes.

Common dialog boxes in Delphi

The common dialog boxes are found on the Dialogs tab of the Component palette. These components take advantage of the standard Windows dialog boxes (located in a DLL in your \Windows\System directory). To use a common dialog box, we need to place the appropriate component (components) on the form. The common dialog box components are nonvisual (don't have a visual design-time interface) and therefore are invisible to the user at runtime.

   TOpenDialog and TSaveDialog  TOpenDialog TSaveDialog
The File Open and File Save dialog boxes have several common properties. File Open is generally used for selecting and opening files. The File Save dialog box (also used as the Save As dialog box) is used when getting a filename from the user in order to save a file. Some of the important properties of the TOpenDialog and TSaveDialog are:

  • The Options properties are very important in determining the final look and feel of the box. For example, a line of code like:

    with OpenDialog1 do
     Options := Options +
       [ofAllowMultiSelect, ofFileMustExist]; 
    

    will keep options already set and allow users to select more than one file in the dialog along with generating an error message if the user tries to select a nonexistent file.

  • The InitialDir property is used to specify the directory that will be used as the initial directory when the file dialog box is displayed. The following code will assure that Initial directory of the Open Dialog box is the Applications start up directory.

      SaveDialog1.InitialDir :=
        ExtractFilePath(Application.ExeName);
    

  • The Filter property contains a list of the file types from which the user can choose. When the user picks a file type from the list, only files of the selected type are displayed in the dialog. The filter can easily be set at design time through the Filter Editor dialog box.
  • Filter Editor

    To create file masks in program code, assign a value to the Filter property that consists of a description and a mask separated by a vertical bar (pipe) character. Like this:

    OpenDialog1.Filter :=
      'Text files (*.txt)|*.txt|All files (*.*)|*.*';
    

  • The FileName property. Once the user clicks the OK button in a dialog box, this property will contain the full path and filename of the file chosen.

       Execute
    To actually create and display common dialog box we need to process the Execute method of the specific dialog box at runtime. Except for TFindDialog and TReplaceDialog, all dialog boxes are displayed modally.

    All the common dialog boxes allow us to determine if the user clicks the Cancel button (or presses ESC). Since Execute method returns True if the user clicked the OK button we have to trap a click on a Cancel button to make sure that given code is not executed.

    if OpenDialog1.Execute then 
      ShowMessage(OpenDialog1.FileName);
    

    This code displays the File Open dialog box and displays a selected filename after a "successful" call to execute method (when the user clicks Open).

    Note: Execute returns True if the user clicked the OK button, double-clicked a file name (in the case of the file dialogs), or pressed Enter on the keyboard. Execute returns False if the user clicked the Cancel button, pressed the Esc key, closed the dialog box with the system close button or with the Alt-F4 key combination.

       From Code
    In order to work with Open dialog (or any other) at runtime without placing an OpenDialog component on the form, we can use the following code:

    procedure TForm1.btnFromCodeClick(Sender: TObject);
    var OpenDlg : TOpenDialog; 
    begin OpenDlg := TOpenDialog.Create(Self); 
     {set options here...}
     if OpenDlg.Execute then begin 
      {code to do something here} 
     end; 
     OpenDlg.Free; 
    end;
    

    Note: Prior to calling Execute, we can (have to) set any of the OpenDialog component's properties.

       TOpenPictureDialog and TSavePictureDialog  TOpenPictureDialog TSavePictureDialog
    These two dialog boxes are nothing more than the regular File Open and File Save dialog boxes with an extra feature: they display a preview window that enables you to see the image that is currently selected.

       My Notepad
    Finally, it's time to do some real coding. The whole idea behind this article (and few others that are to come) is to create a simple MyNotepad application - stand alone Windows like Notepad application.
    In this article we are presented with Open and Save dialog boxes, so let's see them in action:

    MyNotepad at design time

    Steps to create MyNotepad's user interface:
    . Start Delphi and Select File-New Application.
    . Place one Memo, OpenDialog, SaveDialog two Buttons on a form.
    . Rename Button1 to btnOpen, Button2 to btnSave.

       Coding
    1. Use Object Inspector to assign the following code to the FormCreate event:

    procedure TForm1.FormCreate(Sender: TObject);
    begin
     with OpenDialog1 do begin
      Options:=Options+[ofPathMustExist,ofFileMustExist];
      InitialDir:=ExtractFilePath(Application.ExeName);
      Filter:='Text files (*.txt)|*.txt';
     end;
     with SaveDialog1 do begin
      InitialDir:=ExtractFilePath(Application.ExeName);
      Filter:='Text files (*.txt)|*.txt';
     end;
     Memo1.ScrollBars := ssBoth;
    end;
    

    This code sets some of the Open dialog properties as discussed in the beginning of the article.

    2. Add this code for the Onclick event of btnOpen and btnSave buttons:

    procedure TForm1.btnOpenClick(Sender: TObject);
    begin
     if OpenDialog1.Execute then begin
      Form1.Caption := OpenDialog1.FileName;
      Memo1.Lines.LoadFromFile
        (OpenDialog1.FileName);
      Memo1.SelStart := 0;
     end;
    end;
    

    procedure TForm1.btnSaveClick(Sender: TObject);
    begin
     SaveDialog1.FileName := Form1.Caption;
     if SaveDialog1.Execute then begin
       Memo1.Lines.SaveToFile
         (SaveDialog1.FileName + '.txt');
       Form1.Caption:=SaveDialog1.FileName;
     end;
    end;
    

    Run your project. You cannot believe it; files are opening and saving just like with the "real" Notepad.

       Final words
    That's it. We now have our own "little" Notepad. It's true that there is much to add here, but hey this is only the first part. In the next few articles we will see how to add Find and Replace dialog boxes along with how to menu enable our application.

    MyNotepad at runtime
  • ©2014 About.com. All rights reserved.