//---------------------------------------------------------------------------

#include <vcl.h>
#pragma hdrstop

#include "OpenTextFileDialog.h"
//---------------------------------------------------------------------------
#pragma package(smart_init)
#pragma resource "*.dfm"
TForm1 *Form1;
//---------------------------------------------------------------------------
__fastcall TForm1::TForm1(TComponent* Owner)
	: TForm(Owner)
{
}
// BeginExample: TOpenTextFileDialog
// Class: ExtDlgs.TOpenTextFileDialog
// Class: ExtDlgs.TSaveTextFileDialog
// Property: ExtDlgs.TOpenTextFileDialog.Encodings
// Property: ExtDlgs.TOpenTextFileDialog.EncodingIndex
// Method: Classes.TStrings.LoadFromFile

// BeginCode
/*
This example shows how to use the TOpenTextFileDialog and
TSaveTextFileDialog to handle files with specific encodings.
*/
void __fastcall TForm1::FormCreate(TObject *Sender)
{
	openTxtDlg = new TOpenTextFileDialog(this);
	saveTxtDlg = new TSaveTextFileDialog(this);

	// create a new string list that holds encoding info
	TStrings* encodings = new TStringList();

	// add some encodings to the list
	encodings->AddObject("ASCII", TEncoding::ASCII);
	encodings->AddObject("UNICODE", TEncoding::Unicode);
	encodings->AddObject("UTF8", TEncoding::UTF8);

	openTxtDlg->Encodings->Assign(encodings);
	saveTxtDlg->Encodings->Assign(encodings);

	openTxtDlg->Filter = "Text files (*.txt)|*.TXT|XML files (*.xml)|*.XML|Any file (*.*)|*.*";
	saveTxtDlg->Filter = "Text files (*.txt)|*.TXT|XML files (*.xml)|*.XML|Any file (*.*)|*.*";

}

void __fastcall TForm1::Button1Click(TObject *Sender)
{
	if (openTxtDlg->Execute(this->Handle))
	{
		// selecting the filename and encoding selected by the user
		String filename = openTxtDlg->FileName;

		int encIndex = openTxtDlg->EncodingIndex;

		TEncoding* enc = dynamic_cast<TEncoding*>
			(openTxtDlg->Encodings->Objects[encIndex]);

		// checking if the file exists
		if (FileExists(filename))
		{
			// display the contents in a memo based on the selected encoding
			Memo1->Lines->LoadFromFile(filename, enc);
		}
		else
		{
			MessageDlg("File does not exist", mtError,
				TMsgDlgButtons() << mbOK, 0);
		}
	}
}

void __fastcall TForm1::Button2Click(TObject *Sender)
{
	if (saveTxtDlg->Execute(this->Handle))
	{
		// selecting the filename and encoding selected by the user
		String filename = saveTxtDlg->FileName;

		int encIndex = saveTxtDlg->EncodingIndex;

		TEncoding* enc = dynamic_cast<TEncoding*>
			(saveTxtDlg->Encodings->Objects[encIndex]);

		// checking if the file exists
		if (FileExists(filename))
		{
			MessageDlg("File already exists", mtError,
				TMsgDlgButtons() << mbOK, 0);
		}
		else
		{
			// saves to file based on the selected encoding.
			Memo1->Lines->SaveToFile(filename, enc);
		}

	}
}
// EndCode
// EndExample: TOpenTextFileDialog
//---------------------------------------------------------------------------

