Delphi component design preliminary (1)

zhaozj2021-02-08  254

Delphi component design preliminary (1)

Author: Danny Tzu Date: May-2-2002

Foreword

In fact, this article wanted to write it earlier, but the problem of personal abilities and time, it has been dragging no action. This article is not a lot of VCL, but teaches you how to make simple step by Step makes your own components.

Of course, some people have never needed 3-Party components, the reason is that the program can be written directly on another computer without installing components, but Delphi itself is piled up with components. I don't use the custom component. I don't think it is a smart practice.

Write this book because most people who use Delphi will only use components, maybe this is the reason why the Delphi is used, but when designing software, there are many times, as long as it is simple design or modifying components, I can solve the problem. I know someone. Write some shared procedure or function but there will be some restrictions or inconvenience, but I want to write (change) components to know a lot of technologies and principles, especially complete writing component articles books are broken, maybe After retreating, it can also be very simple, and of course, you can write more components and type.

This article does not talk about the use of Interface (the following example is useless), but does not mean that Interface is not important. On the contrary, it is very important. It is mainly what I think this is not suitable for this, if you are interested, you can refer to BRIANCHANG 's "INTERFA" and "Talk about Interface" in Code6421.

Here I will not speak a lot of bad truths, but this doesn't mean you don't need to know some pictures: object orientation, Windows message mechanism, Stream I / O mechanism ... and other related knowledge, if you know how to write The better the component is, although Delphi is known as a visual design, but the write element is not visual, you must be as handmade as purely in the DOS era, maybe it's more familiar with a little older!

Use environment

Delphi 5, 6 All Version recommends that there are many VCL Source Codes to be referenced using Enterprise versions.

let's start

Components are roughly divided into two categories:

Unconventional elements: Unconventional elements are generally related to the system, his feature is not seeing him on the software when Run Time, but it will serve, like TACTIONLIST, TMAINMENU, TPOPMENU, TDATABASE, TQUERY .... and so on. Visual components: visual components and unconventional elements are just opposite, when the Run Time is seen, of course, the Design Time can also be seen, or how you set features (property) and Event, like timage, tdbgrid, tedit .... All.

In fact, you are already writing the component. You may not know yourself. Are you written every day? TFORM is right! Your form is inherited from TFORM components, New Form Unit will generate the following frame code:

Unit unit1;

Interface

Uses

Windows, Messages, Sysutils, Classes, Graphics, Controls, Forms, Dialogs

Type

TFORM1 = Class (TFORM)

Private

{Private Declarations}

public

{Public declarations}

END;

VAR

FORM1: TFORM1;

IMPLEMentation

{$ R * .dfm}

End.

The framework generated by New Component (Component -> New Component) is like this:

Unit CustomControl1;

Interface

Uses

Windows, Messages, Sysutils, Classes, Graphics, Controls, Forms, Dialogs

Type

TCUSTOMCONTROL1 = Class (TCUSTOMCONTROL) PRIVATE

{Private Declarations}

protected

{Protected Declarations}

public

{Public declarations}

Published

{Published Declarations}

END;

PROCEDURE register;

IMPLEMentation

PROCEDURE register;

Begin

Registercomponents ('Samples', [TCUSTOMCONTROL1]);

END;

End.

Do you notice? This two Unit is only poor in TForm, which does not declare Protected, Published these two sectors, because most of the two sections are used when writing Form, so Delphi will omit, but you want If you use it, you can do it yourself! Also because you want to install the relationship of the component disk, CustomControl1 will take more procedure register, but it is necessary to try TFORM cannot be installed into the component disk. This piece you can try. Is there a way to install a component disk, please tell me if you don't need to install, this I want to be a convenient reason, but if you use Delphi package technology, you still need to install this step. This is the same as the component. If you are interested, you can refer to another "delphi package painless use"

First homemade component

First we make a "unconventional element", why do you want to choose "unconventional elements"? The reason is "Simple" because you don't need a lot of technologies. Start who is going to first inherit your father? Because we are If you don't view the elements, you choose Tcomponent for your father, and in the end, it is called "component" that is defined from Tcomponent (inclusive), and other "objects", so "object" contains "components" (white horse non-horse, Hear it!), "Components" and "object" poor can not be installed on "component disk" (but tform is exception, although it is also inherited from tcomponent). First, we must decide to inherit the component, because we want Write "Unconventional Elements", of course, Tcomponent, if you are happy, you can inherit other components, but I believe you have to have more things, we will not find trouble.

1. TAUTOCLOSE Timer Close Components TFORM:

Select New Component's new components in the following screen, which will not be referred to later.

Select the parent element to inherit in Ancestor Type, we choose Tcomponent, enter the component name we have to build in Class Name. By the way, the compilation of the component is the beginning of T, and the component group name of 2-3byte (Custom), it is the name of this component (detailed definition, please refer to Cai Huanlin "Writing Program in accordance with standard write code style", "Delphi 5-write code standard" and "Delphi 5 Component Type"), The reason for this is that Delphi does not allow Class Name to revitalize. If everyone is chartable, the probability of revitalization is very high; but we just demonstrate how to write components omitted the name. But new components and class have What is the relationship, I am so good, the component (object) is the actual work of the class (Class), it is easy to understand!

After setting up, you can select the path and name of the archive in Unit File Name. If you are OK, you can start writing the components, but I will first explain the meaning of each segment:

Unit autoclose;

Interface

Uses

Windows, Messages, Sysutils, Classes, Graphics, Controls, Forms, Dialogs; Type

Tautoclose = Class (Tcomponent)

Private

{Private Declarations}

Private section.

This paragraph can only be seen, including variables, function, procedure, property

The Function used, the Procedure system is automatically stored in the field of this component is defined here such as Text

protected

{Protected Declarations}

Protected area.

Only if you can see and use the [sub-component] side of this component, if you don't open a property, you will not be in the sub-component

The Published section is not asked to hide, which is a bit like a bulk model kit, part, paint, and glue.

Swaquer components are assembled, generally like TCUSTOMXXX (can inherit, but can not be seen on the component disk)

In this section, you can make the sub-components that inherited this component determine those who want to hide, because VCL is not open.

Hide again, for example: Tedit inherits from tcustomedit almost just to announce those who want to open.

public

{Public declarations}

Open segment.

Only when running in Run Time, you can access this section and will not be in Object Inspector (it is Design Time)

That window on the left occurs, a method of generally embodied in this section (Virtual Method)

It can be divided into Virtual and Dynamic (Dynamic), virtual efficiency is fast but take up more resources, I think it may be

There are many places related to the database, the dynamics and virtual opposite, the efficiency is slow but take up less resources, but the current computer speed is very

In the fast, most of the VCL should be used to use a dynamic method, the virtual method can reach [Multi-shape] effect, allowing future generations inherited

The efficiency difference between two types of virtual intendment of Override and Dynamic (Dynamic) is mainly in VMT (Virtual)

Method table, using virtual method, its descendant, whether there is any Override to change, its parents

The entry point of the method (4byte) will appear in the VMT of the child (which is why it will compare the reason for the resource, if there is inheritance

Between the fifth generation, the fifth generation records five points), and the dynamic approach does not change this by Override, the VMT does not appear

The entry point of the law, the system must have this dynamic method to parent in the parent query (of course some time)

Published

{Published Declarations}

Public setting segment (open section)

This segment will appear in Object Inspector, allow User to set up when Design Time, is about long as

Under this:

Property Text: String Read Ftext Write SetText Default '' Stored True;

If only read without Write, it will not appear in Object Inspector, can only be used in Run Time (like

Is the same in the public segment) and this property is read only, default boolean is if set

The value is just that this value will not be stored in .dfm (is Windows Resource File format) can reduce the size of the execution file,

After default, you can pass back the boolean value and the value of the value, for example: ISStoreColor

Stored is set to True (systemically configurable) This property value is stored in .dfm, False will not archive,

DEFAULT and STORED do not have to provide RTTI information in this section, let the system use (discussing the RTTI in another chapter)

READ (Reading Data) and Write (setting data) can be connected to Field variables, such as fText or without parameters

Procedure or Function In order to solve the problem of Procedure and Function cannot pass parameters, Delphi provides an instruction called Index to achieve the purpose of procedure and function sharing, the declaration is as follows (

The program code is in the Implementation section):

Property Text3: String Index 3 ReadText Write setText3;

Property Text2: String Index 2 ReadText Write setText2;

Property text: String Index 1 ReadText Write setText;

END;

PROCEDURE register;

IMPLEMentation

PROCEDURE register;

Begin

Registercomponents ('Samples', [TAUTOCLOSE]);

END;

End.

If you don't understand the above description, it is normal, this doesn't affect the progress behind, it is ok! Start writing.

Because we have to set the time automatic CLOSE FORM, the first thing I think is to use TTIMER, then try it!

Unit autoclose;

Interface

Uses

Windows, Messages, Sysutils, Classes, Graphics, Controls, Forms, Dialogs, ExtCtrls

Type

Tautoclose = Class (Tcomponent)

Private

{Private Declarations}

FTIMER: TTIMER;

protected

{Protected Declarations}

public

{Public declarations}

Published

{Published Declarations}

END;

PROCEDURE register;

IMPLEMentation

PROCEDURE register;

Begin

Registercomponents ('Samples', [TAUTOCLOSE]);

END;

End.

First, in Private, a field (field) called ftimer: timer, but Delphi didn't know TTIMer, pressing F1 on TTIMER to press F1 to put it in an ExtCtrls unit, let's join you!

Come and declare the production and destruction of this component, announcement in public:

Constructor Create (Aowner: Tcomponent); OVERRIDE;

DESTRUCTOR DESTROY; OVERRIDE;

The above name is of course changed, but I don't recommend to change it, because this will make C (already BCB) unable to use this component, because C memory management and Delphi are different. Ok! Now press [Ctrl] [Shift] [ C] Let Delphi help us generate related procedures, and then manually processed into a program:

Private

... 省略 ...

Procedure NewTimer (Sender: TOBJECT);

... 省略 ...

Constructor Tautoclose.create (Aowner: Tcomponent);

Begin

Inherited Create (Aowner);

Ftimer: = TTIMER.CREATE (Self);

Ftimer.enabled: = false;

Ftimer.ontimer: = NewTimer;

END;

Destructor tautoclose.destroy;

Begin

FreeAndnil (fTimer);

Inherited destroy;

Since Timer is the object we have to use, we have to produce yourself, plus the production of TIMER code and time to do what is going to do in the future (content is not anxious first),

We can declare two Property enabled (starting autoclose) and interval (time) to make the user yourself to set up, announced in the Published:

Property enabled: Boolean Read GetENABED WRITE STENABED; Property Interval: Cardinal Read GetInterval Write SetInterval

The same is pressed [Ctrl] [Shift] [C] Let Delphi help us produce related procedures, and then changed to the following:

Function tautoclose.getenabled: boolean;

Begin

Result: = ftimer.enable;

END;

Function tautoclose.getinterval: cardinal;

Begin

Result: = ftimer.interval;

END;

Procedure tautoclose.setenabled (const value: boolean);

Begin

Ftimer.enabled: = value;

END;

Procedure Tautoclose.setInterval (Const Value: Cardinal);

Begin

FTimer.Interval: = Value;

END;

Procedure tautoclose.newtimer (sender: TOBJECT);

Begin

Enabled: = false;

ShowMessage ('Hello My First Component ";

END;

This is based on the element, because the Delphi VCL exists in a package (.bpl) type, so there is a package to accommodate the components we write. Then File -> New, Figure 3:

Choose package to select OK:

The following windows appear to press MOUSE Right to select Save:

Select the file name and location to be stored. It is recommended to save the Projects / BPL.

Back (Figure 5) screen, press Add, appear in the window of Figure 7:

Select [Browse] Add AutoClose.PAS to then OK.

Then select the install mounting component into the component disk.

Ok! The Samples page of the component disk is selected in AutoClose to Form to see if there is normal.

You can put it in Form and there is also these two custom Property in Object Inspector. It should be no problem! Set Enabled to True Test.

You can appear (Figure 10) The dialog is no problem.

But if this element doesn't have a problem in Design Time? Yes, it is necessary to write a little processing, then write TautoClose's truly things to NewTimer, the complete program code is as follows:

Unit autoclose;

Interface

Uses

Windows, Messages, Sysutils, Classes, Graphics, Controls, Forms, Dialogs,

ExtCtrls;

Type

Tautoclose = Class (Tcomponent)

Private

{Private Declarations}

Fenabled: boolean;

FTIMER: TTIMER;

Fontimer: TNotifyEvent; Procedure NewTimer (Sender: TOBJECT);

Function GetInterval: Cardinal

Procedure setnabled (const value: boolean);

Procedure SetInterval (Const Value: Cardinal);

protected

{Protected Declarations}

public

{Public declarations}

Constructor Create (Aowner: Tcomponent); OVERRIDE;

DESTRUCTOR DESTROY; OVERRIDE;

Published

{Published Declarations}

Property enabled: Boolean Read Fenabled Write set1able;

Property Interval: Cardinal Read GetInterval Write SetInterval;

Property ONTIMER: TNOTIFYEVENT Read Fontimer Write Fontimer;

END;

PROCEDURE register;

IMPLEMentation

PROCEDURE register;

Begin

Registercomponents ('Samples', [TAUTOCLOSE]);

END;

{Tautoclose}

Constructor Tautoclose.create (Aowner: Tcomponent);

Begin

Inherited Create (Aowner);

Ftimer: = TTIMER.CREATE (Self);

Ftimer.enabled: = false;

Ftimer.ontimer: = NewTimer;

END;

Destructor tautoclose.destroy;

Begin

FreeAndnil (fTimer);

Inherited destroy;

END;

Function tautoclose.getinterval: cardinal;

Begin

Result: = ftimer.interval;

END;

Procedure tautoclose.setenabled (const value: boolean);

Begin

Fenabled: = Value;

/ / Determine that there is a function when Run Time

IF not (csdesigningin companystate) THEN

Ftimer.enabled: = value;

END;

Procedure Tautoclose.setInterval (Const Value: Cardinal);

Begin

FTimer.Interval: = Value;

END;

Procedure tautoclose.newtimer (sender: TOBJECT);

Begin

Enabled: = false; // First turn the ftimer to avoid rebound triggers.

// If there is a program in ONTIMER execution.

IF assigned (fontimer) THEN

Fontimer;

(Owner as tform) .close;

END;

End.

The above has been removed and declared a FenableD field. This purpose is to let us set Enabled: = True in Design, but will not really trigger ftimer. Of course, ProCedure setENables should also be rewritten. Also add a fontimer, let the user processed some things in front of Form Close; after completion, write a program to test whether this component can operate normally, for example: Setting Enabled: = true in Design Time Will not move Whether the Run Time will be closed when setting time, if there is no problem, this component is complete; but do you think that the constant component icon is a bit ugly, and if each component icon is as long as the User will make a mistake Next to do component icon! Select Image Editor, File -> New -> Component Resource File (.dcr) Press MOUSE Right to Right-click, New -> Bitmap

The pattern length is set to 24 x 24 This is the ICON size that the Delphi component can be accepted.

Press MOUSE Right to Rename Enter Class Name TautoClose

On the class name, press the mouse left button twice, start painting ICON content, you can also press [Ctrl] [i] to zoom in [Ctrl] [u] reduction

The archive file is set to AutoClose.dcr and you can re-install tautoclose's package (mypackage.dpk) with the directory, if AutoClose.dcr is not in Package, you have to manually add, and then look at Samples page:

There is already the above ICON is above ... .. The previous explanation is not just how to write a component, but also contain the program's Debug method and manufacturing process. Although there is a little comparable but the least problem, the comparison will not occur. However, there is a case where the program is finished, and the good program habit is also very important.

Appendix A: Application of Information

Message's application is very wide, accurately said, if there is no message, Borland's VCL should be scheduled!

Most of the information of the message is to make up you in the design of the component, or for the streamline, it is sometimes necessary to handle a lot of components (for example: redrapping elements), if one is dealing with it, It's not a good method, especially the type of components, and use a message is a good choice.

The message can only be sent only to a component or in a broadcast, but the accepted component must have a corresponding handler, and must be the Month of the component, which sounds like the network processing method, yes! Yes .

VCL has actually contained the message processing mechanism inside. In the beginning ancestors of all components (objects) already contains a message processing mechanism, that is, all components have the ability to deal with the message, but the VCL is relatively simple. So it is very simple to use, and then I will demonstrate how to use the message.

Message broadcast within the component:

Broadcasting to be able to do message must be the descendants of TwinControl, broadcasting the Broadcast method, to make broadcasts of the way to write

VAR

MSG: TMESSAGE;

Begin

Msg.msg: = cm_repaint_by_self;

Msg.wparam: = 0;

Msg.lparam: = 0;

Msg.result: = 0;

(Self as twinControl) .Broadcast (msg);

END;

Among them, cm_repaint_by_self; is my own message, of course, you can also use Windows messages, they are defined in Windows.Pas, if you want to define a custom message to be like this

Const

CM_REPAINT_BY_SELF = WM_USER 100; custom message must have until $ 7FFF start with WM_USER 100, I want to use Windows to provide enough, please do not use it outside of this area, because Windows has defined this zone, if the definition There may be problems that have not been able to accept information partial programs like this:

Procedure Wmrepaint_By_self (var message: tMessage); message cm_repaint_by_self;

... 省略 ...

Procedure tahdbedit.wmrepaint_by_self (var message: tMessage);

Begin

INVALIDATE;

END;

The above examples only received a message heavy painting element, of course, you can do a very complicated thing. However, the above example is only limited in a TForm.

to be continued...

2. TDOHOTKEY simple setting HotKey3. TLABEL4. TSTATUSPROCESS plus TProcessBar features 5. Data sensing components: 6. Component Collaboration: 7. Homemade Password Ask For Components: 8. Different Programs (Exe) ), Window (FORM) message broadcast:

转载请注明原文地址:https://www.9cbs.com/read-3120.html

New Post(0)