Changing the Pen Style

From RAD Studio
Jump to: navigation, search

Go Up to Using Pens


A pen's Style property allows you to set solid lines, dashed lines, dotted lines, and so on.

The task of setting the properties of pen is an ideal case for having different controls share same event handler to handle events. To determine which control actually got the event, you check the Sender parameter.

To create one click-event handler for six pen-style buttons on a pen's toolbar, do the following:

  1. Select all six pen-style buttons and select the Object Inspector > Events > OnClick event and in the Handler column, type SetPenStyle.The Code editor generates an empty click-event handler called SetPenStyle and attaches it to the OnClick events of all six buttons.
  2. Fill in the click-event handler by setting the pen's style depending on the value of Sender, which is the control that sent the click event:
procedure TForm1.SetPenStyle(Sender: TObject);
begin
  with Canvas.Pen do
  begin
    if Sender = SolidPen then Style := psSolid
    else if Sender = DashPen then Style := psDash
    else if Sender = DotPen then Style := psDot
    else if Sender = DashDotPen then Style := psDashDot
    else if Sender = DashDotDotPen then Style := psDashDotDot
    else if Sender = ClearPen then Style := psClear;
  end;
end;
void __fastcall TForm1::SetPenStyle(TObject *Sender) {
	if (Sender == SolidPen)
		Canvas->Pen->Style = psSolid;
	else if (Sender == DashPen)
		Canvas->Pen->Style = psDash;
	else if (Sender == DotPen)
		Canvas->Pen->Style = psDot;
	else if (Sender == DashDotPen)
		Canvas->Pen->Style = psDashDot;
	else if (Sender == DashDotDotPen)
		Canvas->Pen->Style = psDashDotDot;
	else if (Sender == ClearPen)
		Canvas->Pen->Style = psClear;
}

The above event handler code could be further reduced by putting the pen style constants into the Tag properties of the pen style buttons. Then this event code would be something like:

void __fastcall TForm1::SetPenStyle(TObject *Sender) {
    if (Sender->InheritsFrom(__classid(TSpeedButton)) Canvas->Pen->Style =
        (TPenStyle)((TSpeedButton*)Sender)->Tag;}

See Also