Home Articles Books Downloads FAQs Tips

Q: Create a TCanvas object for the entire screen (or any other window).


Answer:

The GetDC API function allows you to create a device context for any window. You can then assign this device context to the Handle property of a newly created TCanvas object.

HDC dc = GetDC(0);
Graphics::TCanvas *ScreenCanvas = new Graphics::TCanvas;
ScreenCanvas->Handle = dc;
ScreenCanvas->Pen->Width = 10;
ScreenCanvas->Pen->Color = clRed;
ScreenCanvas->MoveTo(0,0);
ScreenCanvas->LineTo(Screen->Width,Screen->Height);
delete ScreenCanvas;
ReleaseDC(NULL,dc);

You can draw on a specific window by obtaining the window handle and then passing that handle to the GetDC call. This code draws directly onto the Object Inspector if its open.

HWND OIHandle = FindWindow(NULL,"Object Inspector");
if(OIHandle)
{
    HDC dc = GetWindowDC(OIHandle);
    Graphics::TCanvas *OICanvas = new Graphics::TCanvas;
    OICanvas->Handle = dc;
    OICanvas->Pen->Width = 10;
    OICanvas->Pen->Color = clRed;
    OICanvas->MoveTo(0,0);
    OICanvas->LineTo(OICanvas->ClipRect.Right,OICanvas->ClipRect.Bottom);
    delete OICanvas;
    ReleaseDC(OIHandle,dc);
}

Note: Use this code with caution. It works fine, but drawing directly onto another window is something that most programs should avoid.

Note: You must remember to call ReleaseDC for the HDC handle. TCanvas does not release the device context when you delete the TCanvas pointer. You can inspect TCanvas::Destroy to prove this for yourself. (So what about TForm? Does it call ReleaseDC for the HDC that was used to create its Canvas property? No. TForm uses a descendent of TCanvas called TControlCanvas. TControlCanvas automatically calls ReleaseDC in its destructor. TGraphicControl also uses TControlCanvas (look in TGraphicControl::Create)).



Copyright © 1997-2000 by Harold Howe.
All rights reserved.