As a Delphi programmer, if you want to further improve your programming level, you must master how to write controls. This article will introduce some basic methods and patterns of writing controls for beginners through a simple example.
This example control is called TLeiLabel, and it adds two practical functions on the basis of TLabel: one is to make the text have a three-dimensional shape, and the other is to make the text have a hyperlink attribute. Let us implement these functions step by step.
1. Make the text have a three-dimensional shape
First define the type T3DEffect and attribute Style3D as follows:
T3DEffect=(Normal, Raised, Lowered, Shadowed);
PRoperty Style3D:T3DEffect read FStyle3D write SetStyle3D default Normal;
Then define the variable in private: "FStyle3D:T3DEffect;" and set the SetStyle3D() method as follows. This is also the general format for writing methods:
procedure TLeiLabel.SetStyle3D(Value: T3DEffect);
begin
if FStyle3D <> value then
begin
FStyle3D := value;
invalidate; //Indicates that the control will be redrawn
end;
end;
In addition, for text with shadows, the offsets of the shadow, ShadeXOffSet and ShadeYOffSet, must be defined:
property ShadowXOffSet: integer read FXOffSet write SetFXOffSet default 5;
property ShadowYOffSet: integer read FYOffSet write SetFYOffSet default -5;
The writing methods SetFXOffSet() and SetFYOffSet() are similar to SetStyle3D() above.
To redraw a control, you generally need to overload the Paint method. Here we are just redrawing the text. We only need to overload the DoDrawText method.
The declaration of DoDrawText is placed in Protected:
procedure DoDrawText(var Rect: TRect; Flags: Longint); override;
Here DoDrawText() draws different text according to four types (normal, raised, recessed and shadow).
2. Make text have hyperlink attributes
Define an attribute URL to represent the URL or email address to be linked.
Property URL: String read FURL write SetURL;
Write method SetURL as follows:
procedure TLeiLabel.SetURL(Value: String);
Begin
if FURL <> Value then FURL := Value ;
if FURL <> ' then
Cursor := crHandPoint;
end;
When clicking this Label, you need to open a browser or a mail sending and receiving tool, which requires overloading the Click method.
Procedure Click; Override;
procedure TLeiLabel.Click;