why doesn't storing / reusing pen handles work?

23 views
Skip to first unread message

IB

unread,
Jul 16, 2009, 5:22:03 PM7/16/09
to
I create 2 pens, set the canvas pen handle to the first, draw, works ok, the
the canvas pen handle to the second, draw, works ok, set it back to the
first again, and the color and width are lost (get pen black and width 1).
Why is this?

Here's the code:

unit Unit1;

interface

uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs;

type
TForm1 = class(TForm)
procedure FormPaint(Sender: TObject);
private
procedure Test(P:HPen; Y:integer);
{ Private declarations }
public
{ Public declarations }
end;

var
Form1: TForm1;

implementation

{$R *.DFM}

procedure TForm1.Test(P:HPen; Y:integer);
var
R:TRect;
begin
R.Left:=300;
R.Right:=350;
R.Top:=Y+10;
R.Bottom:=Y+50;

Canvas.Pen.Handle:=P;

Canvas.MoveTo(10,Y+10);
Canvas.LineTo(100,Y+10);
Canvas.LineTo(120,Y+30);

Canvas.RoundRect(200, Y+10, 250, Y+50,50,50);
Canvas.FillRect(R);


end;

procedure TForm1.FormPaint(Sender: TObject);
var PH1, PH2: HPEN;
Style : cardinal;
Brush : TLogBrush;
W:integer;

begin
Style := PS_GEOMETRIC or PS_SOLID;
//Style := Style or PS_ENDCAP_SQUARE or PS_JOIN_MITER;
Style := Style or PS_ENDCAP_ROUND or PS_JOIN_ROUND;

Brush.lbStyle := BS_SOLID;
Brush.lbColor := RGB(255,0,0);
Brush.lbHatch := 0;

PH1:= ExtCreatePen(Style, 10, Brush, 0, nil);


Brush.lbColor := RGB(255, 128, 0);

PH2:= ExtCreatePen(Style, 5, Brush, 0, nil);

//Canvas.Brush.Color:= RGB(255,0,255);

Test(PH1, 0);
Test(PH2, 100);

//Brush.lbColor := RGB(255,0,0);
//PH1:= ExtCreatePen(Style, 10, Brush, 0, nil);

Test(PH1, 200);

end;

end.

IB

unread,
Jul 16, 2009, 5:24:03 PM7/16/09
to
Should nave mentioned, this is with Delphi 5

Noener

unread,
Jul 22, 2009, 4:26:35 AM7/22/09
to

You shouldn't really need to be fiddling with the internal handles of
ANY object. Usually ends up with a headache.

When assigning a value to the pen handle, the TPen class frees the
resource the current handle is pointing to.

Therefore: By assigning PH1, you free the original resource. After
that you assign PH2, you free the PH1's resource.

Have a look the TPen.SetHandle in Graphics.pas, and follow the trail
of funtions TResourceManager.ChangeResource()

I recommend you rather use the TPen class, and assigning its
properties using Canvas.Pen.Assign()

pen1 := TPen.Create; //remember to free this later
pen1.Width := 5;
pen1.Color := clBlue;
pen1.Style := etc etc

pen2 := TPen.Create; //remember to free this later
pen2.Width := 15;
pen2.Color := clLime;
pen2.Style := etc etc

Canvas.Pen.Assign(pen1);
//Do some drawing

Canvas.Pen.Assign(pen2);
//Do some drawing

Canvas.Pen.Assign(pen1);
//Do some drawing


Does this help?

Agile Consulting

unread,
Aug 12, 2009, 12:59:32 AM8/12/09
to
hello
Reply all
Reply to author
Forward
0 new messages