UsingDialogs (Delphi)
Description
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 that you can open and save *.txt files or files with any extension. Clicking 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.
Code
procedure TForm1.Button1Click(Sender: TObject);
begin
{ Execute an open file dialog. }
if OpenDialog1.Execute then
{ First check if the 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 the 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;
Uses
- Vcl.Dialogs.TOpenDialog ( fr | de | ja )
- Vcl.Dialogs.TSaveDialog ( fr | de | ja )
- Vcl.Dialogs.TOpenDialog.FileName ( fr | de | ja )
- Vcl.Dialogs.TOpenDialog.Filter ( fr | de | ja )
- Vcl.Dialogs.TOpenDialog.Execute ( fr | de | ja )
- Vcl.Dialogs.TSaveDialog.Execute ( fr | de | ja )