Creating Delphi components. Delphi Reference Guide - Creating Your Own Components

Publication date

Not all forms need to be created when the application starts. Some are better created while the program is running.

In what case is it better to create a form dynamically?

I would highlight two main points.

  1. If the form is rarely used and there is a high probability that it will not be called at all. An example would be the "About" window.
  2. If the number of instances of our window can be more than one.

As always, I will show you how to create a form dynamically with an example.

An example of dynamic form creation.

  1. Click the main menu item "File".
  2. Then new.

The program itself sketched out the class of the future form. Because We will create a window by pressing a button, I suggest removing the following lines of code.

var Form2: TForm2; // If you gave the form a name, then this section of code will vary

We organize the declaration locally, inside the button handler. Let's save the resulting module.

Now let's return to the main form. Let's connect the newly created module to it: File->Use Unit...-> Select the one you need (You can simply add it in the Uses section).

Let's create two buttons. We will create a new window in two different ways:

procedure TForm1.Button1Click(Sender: TObject); var Form2: TForm2; begin Form2:= TForm2.Create(Application);

Form2.Caption:= "New form, method 1";

Form2.Show; end;

procedure TForm1.Button2Click(Sender: TObject); var Form2: TForm2; begin Application.CreateForm(TForm2,Form2); Form2.Caption:= "New form, method 2"; Form2.Show; end; Form2.Caption:= "New form, method 2"; Well, everything is very simple, but if you still have any questions, write in the comments. I will answer once. Form2.Caption:= "New form, method 2"; In the environment Delphi a programmer works with a project - a set of files from which creates an application. One project corresponds to one application. A series of project files, generates and modifies automatically. The programmer can add his own files to the project ( Pascal

-modules,

graphic files DLL – libraries, component libraries, resources, etc.). The project must include the following elements:· main project file with extension .DPR ( D elphi PR

· files of all project forms. For each form, a pair of files of the same name is generated - file Delphi-module with the usual extension .PAS and a form resource file with the extension .DFM ( DLL – libraries, component libraries, resources, etc.). F or M ). Any form of a project should always have its own module-resource file pair. The reverse is not necessary, i.e. the project may include modules and resource files that are not related to any form of the application;

· application resource file (*.RES). It contains application resources that are not included in the forms;

project options file (*.DOF – DLL – libraries, component libraries, resources, etc.). O options F ile). This file stores the values ​​of compiler directives and options, linker settings, names of working directories, parameters command line launch the application.

Example program

Before starting work on the next project, first of all, you should create a separate folder (directory) for the files of the future project. This rule must always be observed, otherwise very soon the files of different projects will be so “mixed” in one directory that it will become quite difficult to sort them by project. We will assume in the future that such a folder has been created, let's call it PO_EVM, this will be the current project folder.

Let's launch Form2.Caption:= "New form, method 2";. If the download was successful, then on the monitor screen we will see what is shown in Fig. 1. In the title bar of the main window Form2.Caption:= "New form, method 2"; there is an inscription Delphi 3 - Project1. This is the name of our project and program. The title bar of the application form window says Form1. If you press the key F12 or click on the button Toggle
Form/Unit
(quick access toolbar) or select a menu item View/Toggle Form/Unit, then the code editor window will move to the foreground and we will see the contents of the page Unit1 editor, which presents Delphi-module code Unit1. Let's add another page to the code editor window, which will contain the code of the main program of the project. To do this, select the menu item View/Project Source. Below is the content of two pages of the code editor: Pascal code main program and Pascal module code main form project, respectively.

Save the project files in the created directory PO_EVM. To do this, press the button Save all on the quick access panel or select the menu item File/Save Project As.... In the appeared standard Windows- in the file saving window, select a folder PO_EVM and save sequentially Delphi-form module code and Delphi-program code in files named IDE_Un1.pas And IDE_Pr.dpr respectively.

program IDE_Pr;

IDE_Un1 in ‘IDE_Un1.pas’ (Form1);

Application.Initialize;

Application.CreateForm(TForm1, Form1);

Application.Run;

unit IDE_Un1;

Windows, Messages, SysUtils,

classes, Graphics, Controls,

TForm1 = class(TForm)

(Private declarations)

(Public declarations)

If you now look at the contents of the folder PO_EVM, then it will contain following files project: IDE_Pr.dof– project options file; IDE_Pr.dpr– main project file; IDE_Pr.res– project resource file; IDE_Un1.pas– Pascal code file for the form module; IDE_Un1.dfm– form resource file.

It is advisable to change some standard environment settings, in particular, so that the process of compiling and linking the program is displayed on the screen, and also so that before each launch of the program for execution, all modified project files are automatically saved. This can be done in the dialog box Environment Options…, which can be called up from the menu Tools/Environment Options…. On the page Preferences In chapter Desktop content set the switch to position Desktop only, In chapter Autosave options install switches at points Editor files And Desktop, and in the section Compiling and Running install a switch Show compiler progress .

The simplest program in Form2.Caption:= "New form, method 2"; is already ready for execution. By pressing the button Run on the Quick Access Toolbar or key F9, you can observe the processes of compilation and linking of the program, after which our program will begin to be executed. Visually, the program is presented on the screen as an empty window with a standard Windows- a title bar containing an application icon, the name of the form, and three window control buttons. Exit the program and return to the environment Form2.Caption:= "New form, method 2"; carried out as standard for Windows way - key combination Alt-F4 or by clicking the close application button. If you now view the contents of the project files folder PO_EVM, then you can notice that two more files have appeared in it: IDE_Un1.dcu and IDE_Pr.exe - a compiled form module file and a boot (executable) application file. The IDE_Pr.exe file can be executed autonomously, i.e. outside the environment Form2.Caption:= "New form, method 2";. After leaving the environment Form2.Caption:= "New form, method 2";, another file is created in the folder IDE_Pr.dsk– file with individual custom settings environment.

Let us give an approximate sequence of actions of a programmer who creates a program “ Calculator +/-“. This application, so to speak, is designed to perform addition and subtraction operations on real numbers. When launched, the program window (form) should look like in Fig. 7.

The form contains three input/output lines (components of the type TEdit) to input two operands and output the result; five buttons (four components type TButton and one - TBitBtn) – reset, indication of the type and result of the operation ( C, + , , = ), exit the program (Close); three labels to indicate the operands and the result (components of type TLabel); separating interface element for highlighting the count result output field (component TBevel).

In its original state, after launch Form2.Caption:= "New form, method 2"; and saving two project files with the specified names, we have an empty form. Next, the order of building the interface part of the application was as follows (the results of your actions can be compared with the location of the components in Fig. 7):

1. Form property Caption in the object inspector we change from the value Form1 to string value Calculator +/-. A change in the form name value is immediately noticeable in the form's title bar;

2. On the page Standard Component palette left-click on the component image Label, then move the mouse pointer to the upper left corner of the form and left-click there. An image of the component will appear at this location on the form. Label with an inscription Label1. The component image is highlighted around the perimeter by six black squares – sizing markers (size markers). Highlighting with markers means that this component is currently active. Using a standard mouse Windows- Using techniques you can change the size of a component and move it around the shape. To activate another form component, simply left-click on it. The contents of the Object Inspector tabs always correspond to the active component; when another component is activated, the composition of the Object Inspector fields automatically changes. Let's change the property Caption component Label from the meaning Label1 to the value 1st operand. Let's give the Name property of this component the value lb_1 .

3. Proceeding similarly, we will place the second component-label slightly lower than the first, setting the properties accordingly Caption And Name values 2nd operand And lb_2 .

4. On the same page Standard Component palette select a component Edit(edit line) and place it on the form to the right of the first label. Property Name assign a value ed_1, and the property Text Let's make it empty.

5. Proceeding similarly, we will position the second edit line to the right of the second label, setting the properties accordingly Text And Name values empty line And ed_2 .

6. On the Additional page of the component palette, select the Bevel component and place it so that it represents the “resulting” line under the second label and the second input line. Property Name, equal Bevel1, we will not change.

7. Below the component Bevel Let’s place another pair “label – input line” to display the result of the calculations. Properties Name let's assign values lb_3 And ed_3, property lb_3.Caption- meaning Result, and the property Text component ed_3– the value of an empty string.

8. Let's place another label to depict the current one. arithmetic operation: (?, +, –) - the operation is not defined, the operation of addition, the operation of subtraction. Let's place this label between the first two labels, closer to the left borders of the components for entering operands (see Fig. 7). Property Name assign a value lb_oper, and the property Caption- meaning ? . Let's also set the subproperty Size in property Font for this label, equal to 14 ;

9. Let's align the components. Standard Windows- Using this method, we select the components – labels. To do this, hold down the button Shift, by sequentially clicking the left mouse button on the label components, we activate all three labels simultaneously. If you now click right click mice, then according to the laws Windows 95 A context menu should appear - and it appears. Let's select the item A lign...(alignment). Now we see a window on the screen Alignment. Select on the panel horizontal paragraph Left sides and press the button Ok. As a result, all three label components will be aligned to the left edge of the leftmost component. Using similar actions, we will align all three edit lines. Editing lines can also be aligned in size by selecting all three of them at the same time and selecting context menu paragraph Size…. The “delicate” work of resizing and moving components is usually performed not with the mouse, but with the cursor keys while the shift keys are pressed, respectively. Shift And Ctrl. These actions can be performed not only with one component, but also with a selected group of components.

10. Now let's place control buttons on the form. We have five of them (see Fig. 7). The first four buttons are the reset button, the operation buttons (addition (+) and subtraction (–)) and the result button. The fifth button is the button to end the program. On the page Standard Component palette, select the Button component and place it to the right of the first edit line. Properties Caption And Name assign values ​​to the buttons accordingly C And btn_Clear. Similarly, we place the other three buttons on the form, calling (property Name) their btn_sum,btn_sub And btn_rez, with names (property Caption) + , And = (see Fig. 7). Having selected the buttons in the group, double-click on the compound property Font in the Object Inspector. In field Size properties Font set the font size 14 points. After setting this value, the size of the symbols on the buttons will increase.

11. The fifth button – the program end button – is selected from the page Additional. This is the first component on this page - a button like BitBtn(command button with inscription and icon). Having positioned the button as shown in Fig. 7, select from the list of property values Kind meaning bkClose. This choice completely determines the visual attributes and functional purpose buttons.

12. To conclude the process of constructing the interface part of the program, we will reduce the shape to the dimensions shown in Fig. 7.

This ends the first stage of creating an application - building the interface. It should be noted that at any stage of interface construction, you can run the program for execution at any time. In the process of performing the steps described above, we did not write a single line or a single Pascal operator. All entries in the application form module text Form2.Caption:= "New form, method 2"; does it herself. At this point, changes have occurred in the interface part of the form module - descriptions of the components we placed in the form and standard modules have been added Delphi Buttons, StdCtrls, ExtCtrls.

Windows, Messages, SysUtils, Classes,

Graphics, Controls, Forms, Dialogs,

Buttons, StdCtrls, ExtCtrls;

TForm1 = class(TForm)

lb_Oper: TLabel;

btn_Clear: TButton;

btn_sum: TButton;

btn_sub: TButton;

btn_rez: TButton;

bb_Close: TBitBtn;

Now the time has come to fill our program with specific content, i.e. implement in the program the operations of addition and subtraction of two operands with the result being written to the output line. The program must respond to very specific events that the user can initiate after starting the program. We will teach the program to respond to the following events: clicks on command interface buttons (we have five of them) and inform the user in case of incorrectly entered operand values ​​(operands must be only numbers). Everything we are going to do is called writing event handler code.

First, let’s verbally specify what should happen when one button or another is pressed, in what cases and with what content messages should appear on the screen:

1. Click on the “Clear” button ( WITH) - clear all three edit lines and display a question mark ( ?) ;

2. Press the “Fold” button ( + ) - change the image of the operation sign to a plus sign (+);

3. Click on the “Subtract” button ( ) - change the image of the operation sign to a minus sign (–);

4. Click on the “Calculate” button ( = ) - check for correctness of data in the first two lines of editing. If the data is correct (numbers), then perform the appropriate arithmetic operation and display the result in the output line. If an error is detected in the source data, a message about this should be displayed indicating the location of the error.

Now let’s translate (translate) each of the above points into Pascal code. Each component has a list of events (the list is provided on the second page ( Events) object inspector) to which it can react (which it can process). Our task is to write code that will be executed when a particular event occurs. For buttons in Form2.Caption:= "New form, method 2"; several event handlers are defined, we will be interested in the “Single click on the button” event handler (clicking the left mouse button while the mouse pointer is over the component Button). This handler is called OnClick. Each event handler is packaged in a separate procedure. The name of this procedure is formed by the environment itself. Form2.Caption:= "New form, method 2";.

Let's write an event handler for a single click on the “Clear” button. To do this, select the “Clear” button on the form ( WITH). Activating the page Events in the Object Inspector window. Double-click on the empty field in the right column next to the inscription OnClick. After that Form2.Caption:= "New form, method 2"; automatically displays the code editor window IDE_Un1 and places a text cursor to insert text inside the TForm1.btn_ClearClick procedure:

procedure TForm1.btn_ClearClick(Sender: TObject);

as if inviting us to start typing from this place Delphi-code of this procedure. Pay attention to the name of the procedure that the environment generated Form2.Caption:= "New form, method 2";. It consists of the name of the form on which the component (button) is located, the name of this component (btn_Clear) and the name of the event handler – Click. Following the content of the first paragraph of our verbal algorithm, insert it into the body of the procedure following lines Delphi-code:

lb_Oper.Caption:=’?’; (operation type is undefined (label – ?))

ed_1.Text:=”; (clear line to enter first operand)

ed_2.Text:=”; (clear line to enter second operand)

ed_3.Text:=”; (clear line to display result)

Proceeding similarly, we will create event handlers for the “Single left-click on a component” event for the “Fold” interface buttons ( + ) and “Subtract” ( ):

– for the “Add” button the line of code is lb_Oper.Caption:=’+’;

– for the “Subtract” button the line of code is lb_Oper.Caption:=’-‘;

Event handler OnClick for the “Calculate” button ( = ) will contain the following Delphi-code:

procedure TForm1.btn_rezClick(Sender: TObject);

Val(ed_1.Text,r1,i);

if i<>0 then begin

ShowMessage('Error in first operand');

Val(ed_2.Text,r2,i);

if i<>0 then begin

ShowMessage('Error in second operand');

case lb_oper.Caption of

‘+’ : ed_3.Text:=FloatToStr(r1+r2);

‘-‘ : ed_3.Text:=FloatToStr(r1-r2);

else ShowMessage('Operation type not defined');

In the TForm1.btn_rezClick event handler, two local real variables r1 and r2 are introduced to store the numeric values ​​of the two operands and an integer variable i for use in Delphi-procedure Val for converting a string variable into a numeric representation. This handler implements the fourth point of the verbal algorithm of the program. First, the string entered by the user and the characters of the first operand are checked for correctness. If this is not a number, then the ShowMessage procedure displays a message corresponding to the situation and the Exit procedure ends the execution of the procedure code. If the data is correct, the variable r1 will take the numeric value of the first operand. The second operand is checked in a similar way and, if everything is normal here, then the variable r2 will take the numeric value of the second operand.

The Case operator implements an arithmetic operation on the variables r1 and r2 depending on which character ( + , , ? ) defines the value of the Caption property of the lb_oper label. If the sign of an arithmetic operation is not defined (for us it is the symbol ? ), then a corresponding message is displayed and the operation is not performed.

It should be noted that, as expected according to the rules Delphi, into the interface part of the form module automatically by the environment Form2.Caption:= "New form, method 2"; procedure headers have been added - keypress event handlers:

procedure btn_sumClick(Sender: TObject);

procedure btn_ClearClick(Sender: TObject);

procedure btn_subClick(Sender: TObject);

procedure btn_rezClick(Sender: TObject);

With this, we can complete the software implementation of the task of creating a simple calculator that performs the operations of adding and subtracting real numbers. We also note that our application is 99% protected from errors associated with operations on incorrect source data (why not 100%?).

Development software for Windows OS and other popular ones can be done using a variety of types of tools. Among those that are very popular among Russian and foreign programmers is the Delphi program. What are the specifics of this development tool? What are its most notable features?

General information about Delphi

Delphi - development environment application programs, which are designed to run on Windows, MacOS, as well as mobile operating systems- iOS and Android. It is characterized by the simplicity of the language and code generation procedures.

If necessary, provides low-level communication with the OS and libraries written in C and C++. Programs created using Delphi do not require third-party shells to run, such as the Java Virtual Machine. Delphi is a development environment that can be successfully used by both professionals and educational purposes. In order to master its basic capabilities, it is not necessary to have high qualifications and knowledge of complex programming languages.

Main advantages

Let's study what the key advantages of the software product in question are. When a particular IT company is justifying the choice of a development environment, Delphi becomes the choice of many programmers and is recommended by them for use. This is due to the fact that this environment allows you to create applications in the most operational deadlines, ensure their high performance even on those computers that have modest hardware specifications. A significant argument in favor of choosing the development environment in question is that it can be supplemented with new tools that are not provided by the standard set of solutions present in the Delphi interface.

Let us now study the nuances of practical use of Delphi capabilities.

Interface specifics

First of all, you can pay attention to some features of the interface of the software development environment in question. Thus, the structure of the program workspace assumes simultaneous work with several main windows. Let's consider this property more details.

The Delphi development environment, version 7 in particular, involves the use of the following key modules: form designer, editor, palette, object inspector, and reference book. In some Delphi modifications, the marked components may be named differently. For example, an editor may correspond to a program code window, and a designer may correspond to a form window. However, their functional purpose will be the same. The Delphi interface elements noted can complement various supporting tools. The first two are considered the main ones from the point of view of program development procedures. But the rest are also important. Let's look at the features of using the marked Delphi modules.

Form designer, editor and palette

With the help of the form designer, the developer creates the interface of his program. In turn, its code is written in the editor. Many programmers who recommend choosing the Delphi development environment as the most optimal solution, as an argument they cite the ease of use of the form designer. Some experts believe that this process is more like a game.

As soon as the user starts creating a program and launches the form designer, initially there are no elements in it, it is empty. But you can immediately fill it out using tools located on another Delphi module - the palette. programs that are configured in the form designer must be controlled by commands, which, in turn, are written in the editor.

But let's return to the palette for now. It can be used to place in the form designer area necessary objects. In order to use a particular tool, you should click once on it - while it is in the palette area, and a second time - in the form designer window. After this, the corresponding object will move to the development area, and you can write code for it in the editor.

Object Inspector

Another significant element that Delphi, an application development environment for Windows and other common platforms, contains is the object inspector. You may notice that the information displayed in it changes: this is affected by the status of the object that is selected in the form designer area.

The structure of the object inspector is as follows. It consists of two windows. Each one contains algorithms that determine the behavior of the corresponding components. The first displays properties, the second displays events. If the programmer wants to make adjustments to the algorithms that affect a specific component, then the capabilities of the object inspector are used. For example, you can change the positioning of certain program interface elements, their height and width.

The Object Inspector has tabs that let you switch between pages that display properties or events that are directly related to the editor. So, if you double-click on the right side of any of the items displayed on the screen, the code that corresponds to a particular event will be recorded in the editor.

Software development in Delphi involves using the Object Inspector to solve problems different tasks. This is predetermined by the fact that with the help of this tool you can change the properties of virtually any objects located on the form, as well as the form itself. Let's take a closer look at some of the features of working with the object inspector.

Object Inspector: Using Features

In order to understand how the Delphi IDE functions in terms of interaction between the Object Inspector and the Form Inspector, you can try making changes to the properties of some common software interface elements in Windows - for example, Memo, Button and Listbox (we will explore their essence in more detail a little later). First you need to place them on the form using available funds Delphi.

You can try experimenting with the Ctl3D property. To do this, you need to click on the form, then go to the object inspector and change the value of the property in question. After this, the form will change significantly. At the same time, the Ctl3D property will be changed on each of the elements that are placed in the design window.

After the experiments have been carried out, we can go back to the form and activate the Ctl3D value. After that, let's look at the Memo and Listbox elements. Now you can change their properties, location on the form, and appearance. For example, by selecting the Edit option in the menu item and then Size, the programmer can change the width and height of objects. There is an option to center them by selecting Edit and Align. The corresponding actions will affect the elements displayed in the Object Inspector.

Using the Delphi module in question, you can change the properties of components. So, for example, if the task is to determine a specific color for them, then there are options for using several tools at once. First, the command corresponding to the color - for example, red - clRed - can be entered into the area Second, the user can select desired color from the list. Thirdly, there is an option to double-click on Color properties— a color selection window will appear. Similarly, the developer can change other attributes of objects - for example, the font type, its color or size.

Directory

Delphi is a development environment that is complemented by quite detailed help system. To access it, select Help from the menu. After this, one of the ones we noted above will be displayed in the window. software modules development environment in question - reference book. The peculiarity of using it is that when you press F1, the user will receive a specific hint reflecting the specifics of using the current tool. For example, if a programmer is working with the Object Inspector, he can select one of the properties, then press F1 and get help information about the corresponding option. The same can be done when working with any other interface element that includes the Delphi 7 development environment and other versions of the corresponding type of software.

Other interface elements

Other significant components of the interface of the software solution in question include a menu, a quick access panel, and an image editor. Regarding the menu, it allows the programmer to quickly access the necessary components present in the structure of the development environment. You can use it either using the mouse or using hot keys. Just below the menu is the quick access panel. Some of its functions duplicate those of the menu, but they are faster to access. Delphi is somewhat similar to Paint program on Windows. That is, with the help of it you can make simple adjustments to pictures, put inscriptions and other elements on them.

Programming Tools

Delphi is a development environment that includes a large number of tools designed to improve programmer productivity. Thus, the key modules we discussed above are complemented by a set of special tools. These include a debugger, a compiler, as well as WinSight and WinSpector components. Note that in some versions of Delphi, the marked elements must be installed separately. Let's study their specifics.

Delphi Debugger

Regarding the debugger, this tool complements the code editor in terms of carrying out the necessary checks of the corresponding software algorithms for correctness. With it, a developer can actually examine his source code line by line. In some cases, when solving a task such as component development, Delphi as an independent product can be supplemented with an external debugger, which gives the programmer enhanced capabilities for checking the code of the software being created.

Delphi compiler

Let us now study the specifics of the compiler of the development environment in question. Note that there may be several corresponding elements in the Delphi structure. So, there is an option to use the DCC compiler, which is useful in cases where the task is to work with the application in an external debugger.

Winsight and WinSpector

The specified modules are those that need to be installed additionally on Delphi. They are characterized by relative difficulty in mastering. However, many programmers who have chosen the Delphi development environment believe that these components must be learned to use. Thus, the Winsight module is used to monitor Windows messages. A component such as WinSpector is needed to record the state of the computer in special file. If you encounter any problems during software development, you can always open this file and see what could be causing the problem.

Standard Components

Delphi development environment, general information that we're learning about has a number of standard components that are also useful to know about. Experts classify these as: MainMenu, PopupMenu, Label, Edit, Memo, Button, Checkbox, Radiobutton, Listbox, Combobox, Scrollbar, Groupbox, Panel, and Scrollbox. Let's study their specifics in more detail.

The MainMenu component is designed to place the main menu in the interface of the created program. To do this, you need to place the corresponding element on the form, then call the Items property through the object inspector, and then determine the necessary menu items.

The PopupMenu component is designed to place pop-up menus in the interface of the created program, that is, those that open by right-clicking the mouse.

The Label component is used to display text in the program window. It can be customized, for example, set desired font in the Object Inspector.

The Edit component is used to display a piece of text on the screen that the user can edit while the program is running. It is complemented by the Memo component, which, in turn, can be used to work with larger texts. This item includes, for example, options such as copying text.

The Button component is designed to perform certain actions by pressing a button while the program is running. It is necessary to place the corresponding element on the form, and then enter the required program code.

The Checkbox component allows you to display lines on the screen with a small window in which a checkbox can be placed using the mouse. A similar element is Radiobutton. They differ, firstly, appearance- the second component is made in the form of a circle, and secondly, the first element allows the simultaneous selection of several options, Radiobutton - only one.

The Listbox component is used to display a list on the screen that the user can scroll through using the mouse. Another element, Combobox, is somewhat similar to it, but it is complemented by the ability to enter text in a special field.

The Scrollbar component is a scroll bar in windows. Typically appears automatically as soon as the text space or form with objects becomes larger than the window.

The Groupbox component is used to record the order in which you move between windows when you press the TAB key. Can be supplemented with a Panel element, which can be used to move several objects on the form.

The Scrollbox component allows you to fix an area on a form that can be scrolled both horizontally and vertically. This property characterizes the main Delphi development windows by default. But if there is a need to enable such an option on a specific section of the form, you can use the Scrollbox component.

Summary

Delphi is a powerful application development environment that is at the same time characterized by ease of use of its core functions. With the help of the tools included in its structure, you can create the most different types programs for Windows and other popular operating systems.

The choice of Delphi development tools by many programmers is determined by the ease of use of the interfaces of the corresponding software, as well as a wide range of tools useful for working at any stage of program creation - at the stage of design, algorithm programming or debugging.

Before creating your component, you need to select an ancestor for it. Who can be the ancestor for your component?

Typically used as ancestors of TComponent, TControl, TWinControl, TGraphicControl, TCustomXXXXXX, as well as all components of the component palette.
Let's take for example the TOpenDialog component, which is located on the Dialogs page of the component palette. It does its job well, but it has one small inconvenience. Each time you use it, you must change the value of the Options property each time. And, as a rule, these are the same actions.
OpenDialog1.Options:= OpenDialog1.Options + ;

so that the file we are trying to open with this dialog actually exists on the disk.
We have already chosen a task for ourselves, all that remains is to create a component. We create a blank for the component by selecting the Component/New Component... command from the menu and selecting in the dialog box
Ancestor type: TOpenDialog
Class Name: TOurOpenDialog
Palette Page: Our Test
We clicked Ok and we now have a template for our future component.

We override the constructor for this component, i.e. in the public section insert the line:

constructor Create(AOwner: TComponent); override;

Clicking on this line Ctrl + Shift + C creates a template for this method, inside which we insert the following lines:

inherited Create(AOwner); (Call the inherited constructor)
Options:= Options + ; (We carry out the actions we need)

Please note: The keyboard shortcuts Ctrl + Shift + up/down arrows allow you to navigate between a method declaration and its implementation.

Installing the created component Component/Install Component...
Install Into New Package
Package file name: C:Program FilesBorlandDelphi4LibOurTest.dpk
Package description: Our tested package

Don't you like that our component has the same icon as the standard one? Then let's create our own for him.
To do this we need to call Tools/Image Editor. Create a new *.dcr file.
Insert the Resource/New/Bitmap image into it. Set the image size to 24x24 pixels. And then - your creativity...
Please note: the color of the dots that matches the color of the dot in the lower left corner of the picture will be considered TRANSPARENT!
Once you've created your drawing, rename it from Bitmap1 to TOurOpenDialog and save the file as OurOpenDialog.dcr.
Remove the component from the package and install it again (only in this case a link to the *.dcr file will be added).
Compile, Install and good luck!

unit OurOpenDialog; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs; type TOurOpenDialog = class(TOpenDialog) private(Private declarations) protected public(Public declarations) constructor Create(AOwner: TComponent); override; published end; procedure register; implementation procedure register; begin RegisterComponents("Samples", ); end; constructor(THOurOpenDialog) begin TOurOpenDialog.Create(AOwner: TComponent); inherited end; end.

Create(AOwner); (Call the inherited constructor) Options:= Options + ; private, protected, public and published. What do they mean?
These are visibility directives.
Everything that is declared in the section private, available only inside the module in which the class is declared (private declarations). Here, as a rule, variables are declared that store property values, as well as methods (procedures or functions) for accessing them.
Everything that is declared in the section protected, is available as in the private section, as well as to the descendants of this class (developer interface).
Here you can declare methods for accessing property values ​​(if you want to allow children of your component to change these methods),
as well as properties, methods and events (methods for reacting to events) in components of type TCustomXXX.
Everything that is declared in the section public, available to any user of the component (runtime interface).
Methods are usually declared here. Only properties and events can be declared in the published section (they are declared as properties).
They are available during application design (design phase interface).

Properties

Type properties massif- regular Object Pascal arrays, but unlike the latter they can be indexed not only by numeric values ​​but also by string ones. Unfortunately, this type of property requires a custom property editor (in the Object Inspector, the property editor has a button with three dots [...]), so in the example below the property ArrayProp announced in section public.

type TOurComponent = class(TComponent) private( Private declarations ) FArrayProp: array of integer; function GetArrayProp(aIndex: integer): integer; procedure SetArrayProp(aIndex: integer; const Value: integer); protected(Protected declarations) public(Public declarations) property ArrayProp: integer read GetArrayProp write SetArrayProp; published(Published declarations) end;

Property specifiers

Specifier default specifies whether to save the property value in the form file or not. If the property value matches the value default- the value in the form file is not saved, if the values ​​are not equal - it is saved. You can check this by placing the component on the form and selecting the "View as Text" menu item with the right mouse button. Default does not set the initial value of the property to the specified one. This must be done in the component's constructor.

unit OurComponent; interface uses Windows, SysUtils, Classes, Graphics, Forms, Controls; type TOurComponent = class(TComponent) private( Private declarations ) FMyInteger: Integer; protected(Protected declarations) public(Public declarations) constructor Create(AOwner: TComponent); override; published(Published declarations) property MyInteger: Integer read FMyInteger write FMyInteger default 10; end; implementation constructor TOurComponent.Create(AOwner: TComponent); begin TOurOpenDialog.Create(AOwner: TComponent); Create(AOwner); end; end.

Specifier FInteger:= 10; nodefault
overrides the default property value. This specifier is typically used to override the default value of an inherited property. property For example: FInteger:= 10;;

Specifier stored specifies when to save the property value in the form file. After stored can stand true(always save) false(never save) or the name of a function that returns a Boolean result.

property OneProp: integer read FOneProp write SetOneProp stored False; property TwoProp: integer read FTwoProp write SetTwoProp stored True; property ThreeProp: integer read FThreeProp write SetThreeProp stored Fuct;

And the last thing:
To add a picture to a component for demonstration in the component panel, you need to: - create it with a size of 24*24 with the file name.dcr (in the resource, the name of the picture is equal to the name of the component, in capital letters)
- place the picture next to the component.

Often, when working with big amount files or just for organization, it is necessary to distribute files into separate directories and subdirectories. To automate the process, it is convenient for the program to be able, if necessary, to independently create the directories it needs for storing files. Delphi has a set of functions to support this task.

Creating a folder

You can create a folder in Delphi using the CreateDir function or the MkDir procedure. You can also use the ForceDirectories function. The first two commands correctly create one new folder. The differences are in how they behave if it is impossible to create a folder.

ForceDirectories(ExtractFilePath(Application.ExeName) + "/folder1/folder2/newfolder" );

Deleting a folder

When deleting a folder, it is important to consider whether it contains attachments or not. If the folder is empty, then the RemoveDir function is used, in which, similar to creation, the path to the folder to be deleted is indicated. The function, when executed, also returns True if the deletion was successful and False if the deletion was unsuccessful.

if RemoveDir("myfolder" ) then
ShowMessage( "The folder was successfully deleted.")
else
ShowMessage( "Error: folder not deleted.");

If the folder is not empty, then you can use a custom function that will sequentially delete all attached files, and then empty folders. For Delphi environments 2010, you can use the following method:

TDirectory.Delete("myfolder" , True);

In this case, the IOUtils library should be added in the descriptions section.

uses IOUtils;

If this is not possible, you should use the following function, described in DelphiWorld. The parameter specifies the path to the folder to be deleted. If the deletion is successful (including all attachments), the function will return True; if the deletion is unsuccessful, it will return False.

// Function for deleting a directory with attachments.
function MyDirectoryDelete(dir: string): Boolean;
var
fos: TSHFileOpStruct;
begin
ZeroMemory(@fos, SizeOf(fos));
with fos do begin
wFunc:= FO_DELETE;
fFlags:= FOF_SILENT or FOF_NOCONFIRMATION
pFrom:= PChar(dir + #0);
end ;
Result:= (0 = ShFileOperation(fos));
end ;

// Call the delete function in the program.
begin if MyDirectoryDelete("myfolder" ) then
ShowMessage( "The folder was successfully deleted.")
else
ShowMessage( "Error: folder not deleted.");
end ;

You need to add the ShellApi library to the descriptions section here.

uses
ShellApi;

Checking the existence of a directory

To check the existence of a directory, use the DirectoryExists function. The parameter also indicates the full or relative path to the folder. If specified folder exists, the function will return True, otherwise False.

if DirectoryExists("myfolder" ) then
ShowMessage( "The folder exists.")
else
ShowMessage( "There is no such folder.");