unit TOleContainerExample;

interface

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

type
  TForm1 = class(TForm)
    OleContainer1: TOleContainer;
    OpenDialog1: TOpenDialog;
    SaveDialog1: TSaveDialog;
    MainMenu1: TMainMenu;
    File1: TMenuItem;
    Open1: TMenuItem;
    Save1: TMenuItem;
    N1: TMenuItem;
    Exit1: TMenuItem;
    procedure Exit1Click(Sender: TObject);
    procedure Open1Click(Sender: TObject);
    procedure Save1Click(Sender: TObject);
    procedure FormCreate(Sender: TObject);
  private
    { Private declarations }
  public
    { Public declarations }
  end;

var
  Form1: TForm1;

implementation

{$R *.dfm}

// BeginExample: TOleContainer
// Method: OleCtnrs.TOleContainer.CreateObjectFromFile
// Method: OleCtnrs.TOleContainer.SaveAsDocument
// BeginCode
{
This example uses an OLE container and a main menu on a form.
When the user clicks the Open or Save options in the main menu,
an open/save dialog is displayed and by default,
the user is required to enter the name of a Word document.
Files with other extensions supported by the OLE container
can also be accessed. An additional test is made to assure that
the file to open exists and that no file overwriting is
going to take place.
}
procedure TForm1.Exit1Click(Sender: TObject);
begin
  Close;
end;

procedure TForm1.FormCreate(Sender: TObject);
begin
  OpenDialog1.Filter := 'Documents (*.doc)|*.DOC|Any file (*.*)|*.*';
  SaveDialog1.Filter := 'Documents (*.doc)|*.DOC|Any file (*.*)|*.*';
end;

procedure TForm1.Open1Click(Sender: TObject);
begin
  if OpenDialog1.Execute then
    if FileExists(OpenDialog1.FileName) then
      OleContainer1.CreateObjectFromFile(OpenDialog1.FileName, false)
    else
      raise Exception.Create('File not found.');
end;

procedure TForm1.Save1Click(Sender: TObject);
begin
  if SaveDialog1.Execute then
    if FileExists(SaveDialog1.FileName) then
      raise Exception.Create('File already exists. Cannot overwrite.')
    else
      OleContainer1.SaveAsDocument(SaveDialog1.FileName);
end;
// EndCode
// EndExample: TOleContainer

end.
