tags:

views:

69

answers:

1

Hi

Using the following code in Delphi 2007:


procedure TfrmTest.PaintBox1Paint(Sender: TObject);
const
  Rect_Size = 10;
begin
  PaintBox1.Canvas.Brush.Color := clYellow;
  PaintBox1.Canvas.FillRect(Rect(0, 0, PaintBox1.width, PaintBox1.height));

  PaintBox1.Canvas.Brush.Color := clRed;
  DrawARect(PaintBox1.Canvas, 0, 0, Rect_Size, Rect_Size);
end;

procedure TfrmTest.DrawARect(ACanvas: TCanvas; iLeft, iTop, iWidth, iHeight: Integer);
var
  rgnMain: HRGN;
begin
  rgnMain := CreateRectRgn(iLeft, iTop, iLeft + iWidth, iTop + iHeight);
  try
    SelectClipRgn(ACanvas.handle, rgnMain);
    ACanvas.FillRect(ACanvas.ClipRect);
    SelectClipRgn(ACanvas.handle, 0);
  finally
    DeleteObject(rgnMain);
  end;
end;

I get this: (Yellow area shows boundaries of PaintBox1).

alt text

(Image shows a form with a yellow box [PaintBox1] in the center. However my red rectange [rgnMain] has been drawn at pos 0,0 on the form)

My expectation was that the red rectangle would be at the top left of the PaintBox1 canvas, not the form's canvas. Why is it not? Can regions only be used with controls that have a Windows handle?

Thanks

+2  A: 

Device Contexts require a window handle. What VCL does for non-windowed controls is to offset the view port of the DC acquired for the TWinControl they are on, by using SetWindowOrgEx in TWinControl.PaintControls. The new view port is in logical units. So for 'TGraphicControl's, which does not descend from TWinControl, you can use GDI functions which work on logical coordinates. See the remarks section for SelectClipRgn, which says the coordinates should be specified in device units. You'd offset the region or the coordinates.

Sertac Akyuz
Thanks Sertac, that explains it
Xanyx