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

#include <vcl.h>
#pragma hdrstop

#include "GetDeviceContext.h"
//---------------------------------------------------------------------------
#pragma package(smart_init)
#pragma resource "*.dfm"

// BeginExample: GetDeviceContext
// Method: Graphics.TCanvas.Create
// Method: Controls.TControl.GetDeviceContext
// Method: Controls.TWinControl.GetDeviceContext
// Property: Graphics.TCanvas.Handle
// Property: Graphics.TGraphic.Palette

// BeginCode
/*
The GetFormImage allows you to easily obtain a bitmap of a
form. The following method can be added to a custom
TWinControl descendant to save itself as a bitmap.  Check the
produced BMP file to confirm.  Click the button and them
double click on the newly created foo.bmp file to view.
*/

#include <memory>       //for STL auto_ptr class

class TMyControl : public TColorListBox
{
__published:	// IDE-managed Components
	void __fastcall SaveAsBmp(TFileName fileName);
private:	// User declarations
public:		// User declarations
	__fastcall TMyControl(TComponent* Owner);
};

TForm1 *Form1;
TMyControl *MyControl1;

__fastcall TForm1::TForm1(TComponent* Owner)
	: TForm(Owner)
{
}

__fastcall TMyControl::TMyControl(TComponent* Owner)
	: TColorListBox(Owner)
{
}

typedef struct {
  TLogPalette lpal;
  TPaletteEntry dummy[256];
} LogPal;

void __fastcall TMyControl::SaveAsBmp(TFileName fileName)
{
  std::auto_ptr<TCanvas> tempCanvas(new TCanvas);
  HWND notUsed;
  tempCanvas->Handle = GetDeviceContext(notUsed);
  std::auto_ptr<TImage> image2save(new TImage(Form1)); // The owner will clean this up.
  image2save->Height = Height;
  image2save->Width = Width;
  TRect destRect = Rect(0,0,Width,Height);
  TRect sourceRect = destRect;
  image2save->Canvas->CopyRect(destRect, tempCanvas.get(), sourceRect);
  LogPal SysPal;
  SysPal.lpal.palVersion = 0x300;
  SysPal.lpal.palNumEntries = 256;
  GetSystemPaletteEntries(tempCanvas->Handle,0,256,SysPal.lpal.palPalEntry);
  image2save->Picture->Bitmap->Palette =
	CreatePalette(dynamic_cast<const tagLOGPALETTE *>(&SysPal.lpal));
  image2save->Picture->SaveToFile(fileName);
}

void __fastcall TForm1::Button1Click(TObject *Sender)
{
  static_cast<TMyControl*>(MyControl1)->SaveAsBmp("../foo.bmp");
}

void __fastcall TForm1::FormCreate(TObject *Sender)
{
  TMyControl* control = new TMyControl(Form1); // The owner will clean this up.
  
  MyControl1 = control;
  control->Parent = this;
  control->Visible = true;
}
// EndCode
// EndExample: GetDeviceContext
//---------------------------------------------------------------------------

