UsingDialogs (C++)
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, in order to open and save *.txt files or files with any extension. Clicking the Open/Save button executes the open/save dialog. An exception is thrown when trying to open a file that does not exist or when trying to overwrite a file using the save dialog.
Code
__fastcall TForm1::TForm1(TComponent* Owner)
: TForm(Owner)
{
// 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 (*.*)|*.*";
}
void __fastcall TForm1::Button1Click(TObject *Sender)
{
// Execute an open file dialog.
if (OpenDialog1->Execute())
// First, check if the file exists.
if (FileExists(OpenDialog1->FileName))
// If it exists, load the data into the memo box.
Memo1->Lines->LoadFromFile(OpenDialog1->FileName);
else
// Otherwise, throw an exception.
throw(Exception("File does not exist."));
}
void __fastcall TForm1::Button2Click(TObject *Sender)
{
// Execute a save file dialog.
if (SaveDialog1->Execute())
// First, check if the file exists.
if (FileExists(OpenDialog1->FileName))
// If it exists, throw an exception.
throw(Exception("File already exists. Cannot overwrite."));
else
// Otherwise, save the memo box lines into the file.
Memo1->Lines->SaveToFile(SaveDialog1->FileName);
}
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 )