unit UsingDialogsExample;

interface

uses
  Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
  Dialogs, StdCtrls;

type
  TForm1 = class(TForm)
    Button1: TButton;
    Button2: TButton;
    Memo1: TMemo;
    OpenDialog1: TOpenDialog;
    SaveDialog1: TSaveDialog;
    procedure Button1Click(Sender: TObject);
    procedure Button2Click(Sender: TObject);
    procedure FormCreate(Sender: TObject);
  private
    { Private declarations }
  public
    { Public declarations }
  end;

var
  Form1: TForm1;

implementation

{$R *.dfm}

// BeginExample: UsingDialogs
// Class: Dialogs.TOpenDialog
// Property: Dialogs.TOpenDialog.Filter
// Method: Dialogs.TOpenDialog.Execute

// BeginCode
{
This example uses a memo box, two buttons, an open dialog
and a save dialog on a form. When the application runs,
the open dialog and save dialog filters are initialized,
so to open and save *.txt files or files with any extension.
Clicking on the Open/Save button executes the open/save dialog.
An exception is raised when trying to open a file that
does not exist, or when trying to overwrite a file using the
save dialog.
}
procedure TForm1.Button1Click(Sender: TObject);
begin
  { execute an open file dialog }
  if OpenDialog1.Execute then
    { first check if file exists }
    if FileExists(OpenDialog1.FileName) then
      { if it exists, load the data into the memo box }
      Memo1.Lines.LoadFromFile(OpenDialog1.FileName)
    else
      { otherwise raise an exception }
      raise Exception.Create('File does not exist.');
end;

procedure TForm1.Button2Click(Sender: TObject);
begin
  { execute a save file dialog }
  if SaveDialog1.Execute then
    { first check if file exists }
    if FileExists(SaveDialog1.FileName) then
      { if it exists, raise an exception }
      raise Exception.Create('File already exists. Cannot overwrite.')
    else
      { otherwise, save the memo box lines into the file }
      Memo1.Lines.SaveToFile(SaveDialog1.FileName);
end;

procedure TForm1.FormCreate(Sender: TObject);
begin
  {
  initialize the dialog filters to open/save *.txt files
  and also files with arbitrary extension
  }
  OpenDialog1.Filter := 'Text files (*.txt)|*.TXT|Any file (*.*)|*.*';
  SaveDialog1.Filter := 'Text files (*.txt)|*.TXT|Any file (*.*)|*.*';
end;
// EndCode
// EndExample: UsingDialogs

end.
