GetDeviceContext (C++)

From RAD Studio Code Examples
Jump to: navigation, search

Description

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 then double-click the newly created foo.bmp file to view.


Code

#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 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");
}

__fastcall TForm1::TForm1(TComponent* Owner)
  : TForm(Owner)
{
  TMyControl* control = new TMyControl(Form1); // The owner will clean this up.
  
  MyControl1 = control;
  control->Parent = this;
  control->Visible = true;
}

Uses

Personal tools
Assistance