uses delphi что это
Файл проекта Uses в Delphi
Типичный головной файл (*.dbr) имеет вид:
Program Proect1; (имя программы)
Begin
//операторы
End.
По сути в этом файле присутствует информация инициализации приложения, создания форм и запуска приложения. Сразу Вам скажу, что при сохранении проекта, вам надо придумать название, а для модулей Unit1 – то же, только не делайте так, чтобы имена совпали. Пример: Unit1 я назвал как my, а проект — уже с этим именем не сохранится.
Uses
Forms,
Unit1 in ‘Unit1.pas’
После заголовка идет uses – подключение модуля или модулей. Каждое имя подключаемого модуля перечисляется через запятую. Можно также указать модуль из файла, т. е. сам модуль находится в Unit1 in ‘c:\example\unit1.pas’. В случае, как я решил, показать, что на форме два модуля: в разделе implementation укажем uses my, а в my я указываю, что uses unit1.
Теперь оба модуля связаны между собой.
А теперь коротко о главном:
Пример структуры:
Unut ;
interface // Открытый интерфейс модуля
implementation //реализация модуля
initialization//не обязательный
finalization //не обязательный
. раздел interface в модуле обязателен или нет раздел File в Delphi раздел инициализации delphi
Unit delphi
Delphi 7. Занятие 2_5. Часть 1.
Подключения стандартного модуля — delphi unit uses
Мы уже говорили, что кроме кода, написанного программистом, для работы программы требуется множество стандартных процедур и функций.
Например, преобразование целого числа в строку символов — функция «IntToStr()».
Код этой функции находится в модуле SysUtils, указанном в предложении uses.
unit Unit1;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, Menus, StdCtrls, Buttons, ExtCtrls;
Если попробовать загрузить картинку в таком формате, компилятор выдаст ошибку.
К счастью, имеется модуль «JPEG», подключение которого решает проблему:
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,Dialogs, Menus, StdCtrls, Buttons, ExtCtrls, JPEG;
Для просмотра «.png» картинок надо скачать в интернете модуль TPNGImage и подключить его наподобие модуля JPEG.
Интерфейс главной формы проекта.
При своём открытии среда IDE Delphi автоматически создаёт форму с именем Form1, которая будет являться главной формой программы (то есть её закрытие приводит к закрытию всей программы).
Разместим на ней все необходимые нам компоненты:
Во первых, это главное меню «TmainMemu». Далее, это панель, на которой расположим компонент «Tmemo». В нём будет размещено краткое справочное описание разрабатываемой нами программы.
Дополнительно используем две кнопки «BitBtn». Воспользуемся свойством «Kind» этого компонента. Для кнопки, расположенной на панели, установим значение «bkOK». Для второй установим «bkClose». Кнопка такого вида будет закрывать форму автоматически при её нажатии.
Сделаем так, чтобы панель «Panel1»не была видима при запуске программы. Для этого в инспекторе объектов установим свойство панели «Visible» в «false».
Если пользователь захочет посмотреть краткое описание программы, он должен выбрать пункт меню «О программе».
Main menu delphi
Создание главного меню формы.
Разместим на «Form1» компонент главное меню (MainMenu).
Прежде мы управляли действиями программы, нажимая на кнопки, теперь же будем делать это, выбирая пункты меню.
Для создания пунктов меню необходимо вызвать редактор, дважды щёлкнув по компоненту MainMenu1 или выбрать пункт «Items …» в окне ObjeсtInspector.
В открывшемся окне щелкаем по прямоугольнику и он окрашивается в голубой цвет:
В инспекторе объектов заполняем свойство «Caption» значением «Перейти» и нажимаем «Enter». Поле заполнится введённым значением.
Далее выделяем прямоугольник, расположенный справа и в «Caption» в инспекторе объектов вводим значением «О программе».
Появляется пункт подменю:
Подпункты подменю заполняются аналогично пунктам меню, вводя туда два значения: «ко второй форме» и «завершить программу».
Здесь приведём обработчики обработчики «кликов» по пунктам меню.
Обработчики пунктов меню.
Обработчики пунктов меню вызываются так же, как и для кнопки: двойным щелчком по пункту (если вдруг редактор пунктов меню исчез, то он вызывается вновь двойным щелчком по компоненту MainMenu).
Обработчики задаём для пунктов подменю.
Для пункта «ко второй форме»:
procedure TForm1.N3Click(Sender: TObject);
form2.Show;
Обработчик второго пункта меню «завершить программу»:
procedure TForm1.N4Click(Sender: TObject);
close; //процедура завершения программы.
Второй пункт главного меню «о программе»
procedure TForm1.N5Click(Sender: TObject);
self.Panel1.Visible:=true; //панель становится видимой.
Обработчик «клика» кнопки «ok»:
procedure TForm1.BitBtn1Click(Sender: TObject);
self.Panel1.Visible:=false; // делаем панель снова невидимой.
обработчик события для кнопки «Close» писать не надо. При выборе такого типа кнопки её срабатывание происходит автоматически и программа будет закрыта.
Создание второй, третьей и так далее форм и модулей.
В предыдущем разделе мы создали главную форму программы. Однако реальные программы часто содержат две и более форм.
Создадим вторую форму. Для этого в пункте главного меню IDE выберем пункт «File» и в нём пункт «New» и далее в открывающемся подменю пункт «Form».
Будет создана вторая форма с именем «Form2» и соответствующий ей модуль «Unit2».
Но модуль не обязательно должен быть привязан к форме. Создадим самостоятельный модуль «Unit3». Для этого опять воспользуемся главным меню «File» > «New» > «Unit».
Связь модулей между собой.
Если в созданных модулях написать программный код, то он никак не будет связан между собой. Пока модули не могут видеть друг друга.
Но попытка компиляции выдаст ошибку, так как в модуле «Unit1» ничего не известно о существовании «Unit2».
Аналогично добавляется ссылка на модуль «Unit3».
Предложение будет добавлено в секцию «implementation», а не в главное предложение «Uses» в секции «Interface» в связи со следующими соображениями.
Circular unit reference delphi — перекрёстные ссылки.
Существует проблема перекрёстных ссылок на модули.
Предположим, в модуле 2 есть данные, которые используются для работы процедур, расположенных в модуле 1.
Тогда в модуле 1 в предложении uses надо сделать ссылку на модуль 2. В принципе, это можно сделать в uses, расположенном в секции interface.
Всё будет нормально, пока не потребуется получить из модуля 2 доступ к данным, расположенным в модуле 1. Если сделать ссылку на модуль 1 в секции interface модуля 2, то в силу особенностей компилятора он выдаст ошибку «о недопустимости перекрёстных ссылок».
Решение этой проблемы весьма тривиально. Необходимо размещать ссылки на модули в секции implementation, что и происходит автоматически при использовании команды главного меню «File» > «Use Unit …».
Programs and Units (Delphi)
This topic covers the overall structure of a Delphi application: the program header, unit declaration syntax, and the uses clause.
Contents
Program Structure and Syntax
Note: Strictly speaking, you need not explicitly use any units in a project, but all programs automatically use the System unit and the SysInit unit.
The source code file for an executable Delphi application contains:
The Program Heading
The program heading specifies a name for the executable program. It consists of the reserved word program, followed by a valid identifier, followed by a semicolon. For applications developed using Embarcadero tools, the identifier must match the project source file name.
Delphi project files are usually short, since most of a program’s logic resides in its unit files. A Delphi project file typically contains only enough code to launch the application’s main window, and start the event processing loop. Project files are generated and maintained automatically by the IDE, and it is seldom necessary to edit them manually.
In standard Pascal, a program heading can include parameters after the program name:
Embarcadero’s Delphi ignores these parameters.
In RAD Studio, the program heading introduces its own namespace, which is called the project default namespace.
The Program Uses Clause
The uses clause lists those units that are incorporated into the program. These units may in turn have uses clauses of their own. For more information on the uses clause within a unit source file, see Unit References and the Uses Clause, below.
The uses clause consists of the keyword uses, followed by a comma delimited list of units the project file directly depends on.
The Block
The block contains a simple or structured statement that is executed when the program runs. In most program files, the block consists of a compound statement bracketed between the reserved words begin and end, whose component statements are simply method calls to the project’s Application object. Most projects have a global Application variable that holds an instance of Vcl.Forms.TApplication, Web.WebBroker.TWebApplication, or Vcl.SvcMgr.TServiceApplication. The block can also contain declarations of constants, types, variables, procedures, and functions; these declarations must precede the statement part of the block. Note that the end that represents the end of the program source must be followed by a period (.):
Unit Structure and Syntax
A unit file begins with a unit heading, which is followed by the interface keyword. Following the interface keyword, the uses clause specifies a list of unit dependencies. Next comes the implementation section, followed by the optional initialization, and finalization sections. A skeleton unit source file looks like this:
The unit must conclude with the reserved word end followed by a period.
The Unit Heading
The unit heading specifies the unit’s name. It consists of the reserved word unit, followed by a valid identifier, followed by a semicolon. For applications developed using Embarcadero tools, the identifier must match the unit file name. Thus, the unit heading:
The Interface Section
The interface section of a unit begins with the reserved word interface and continues until the beginning of the implementation section. The interface section declares constants, types, variables, procedures, and functions that are available to clients. That is, to other units or programs that wish to use elements from this unit. These entities are called public because code in other units can access them as if they were declared in the unit itself.
The interface declaration of a procedure or function includes only the routine’s signature. That is, the routine’s name, parameters, and return type (for functions). The block containing executable code for the procedure or function follows in the implementation section. Thus procedure and function declarations in the interface section work like forward declarations.
The interface declaration for a class must include declarations for all class members: fields, properties, procedures, and functions.
The interface section can include its own uses clause, which must appear immediately after the keyword interface.
The Implementation Section
The implementation section of a unit begins with the reserved word implementation and continues until the beginning of the initialization section or, if there is no initialization section, until the end of the unit. The implementation section defines procedures and functions that are declared in the interface section. Within the implementation section, these procedures and functions may be defined and called in any order. You can omit parameter lists from public procedure and function headings when you define them in the implementation section; but if you include a parameter list, it must match the declaration in the interface section exactly.
In addition to definitions of public procedures and functions, the implementation section can declare constants, types (including classes), variables, procedures, and functions that are private to the unit. That is, unlike the interface section, entities declared in the implementation section are inaccessible to other units.
The implementation section can include its own uses clause, which must appear immediately after the keyword implementation. The identifiers declared within units specified in the implementation section are only available for use within the implementation section itself. You cannot refer to such identifiers in the interface section.
The Initialization Section
The initialization section is optional. It begins with the reserved word initialization and continues until the beginning of the finalization section or, if there is no finalization section, until the end of the unit. The initialization section contains statements that are executed, in the order in which they appear, on program start-up. So, for example, if you have defined data structures that need to be initialized, you can do this in the initialization section.
For units in the interface uses list, the initialization sections of the units used by a client are executed in the order in which the units appear in the client’s uses clause.
The Finalization Section
The finalization section is optional and can appear only in units that have an initialization section. The finalization section begins with the reserved word finalization and continues until the end of the unit. It contains statements that are executed when the main program terminates (unless the Halt procedure is used to terminate the program). Use the finalization section to free resources that are allocated in the initialization section.
Finalization sections are executed in the opposite order from initialization sections. For example, if your application initializes units A, B, and C, in that order, it will finalize them in the order C, B, and A.
Once a unit’s initialization code starts to execute, the corresponding finalization section is guaranteed to execute when the application shuts down. The finalization section must therefore be able to handle incompletely initialized data, since, if a runtime error occurs, the initialization code might not execute completely.
Unit References and the Uses Clause
A uses clause lists units used by the program, library, or unit in which the clause appears. A uses clause can occur in
Most project files contain a uses clause, as do the interface sections of most units. The implementation section of a unit can contain its own uses clause as well.
Case Sensitivity: In unit declarations and uses clauses, unit names must match the file names in case. In other contexts (such as qualified identifiers), unit names are case insensitive. To avoid problems with unit references, refer to the unit source file explicitly:
If such an explicit reference appears in the project file, other source files can refer to the unit with a simple uses clause that does not need to match case:
The Syntax of a Uses Clause
A uses clause consists of the reserved word uses, followed by one or more comma delimited unit names, followed by a semicolon. Examples:
In the uses clause of a program or library, any unit name may be followed by the reserved word in and the name of a source file, with or without a directory path, in single quotation marks; directory paths can be absolute or relative. Examples:
Use the keyword in after a unit name when you need to specify the unit’s source file. Since the IDE expects unit names to match the names of the source files in which they reside, there is usually no reason to do this. Using in is necessary only when the location of the source file is unclear, for example when:
In the uses clause of a unit, you cannot use in to tell the compiler where to find a source file. Every unit must be in the compiler’s search path. Moreover, unit names must match the names of their source files.
Multiple and Indirect Unit References
A uses clause need include only units used directly by the program or unit in which the clause appears. That is, if unit A references constants, types, variables, procedures, or functions that are declared in unit B, then A must use B explicitly. If B in turn references identifiers from unit C, then A is indirectly dependent on C; in this case, C needn’t be included in a uses clause in A, but the compiler must still be able to find both B and C in order to process A.
The following example illustrates indirect dependency:
When a change is made in the interface section of a unit, other units that depend on the change must be recompiled. But when changes are made only in the implementation or other sections of a unit, dependent units don’t have to be recompiled. The compiler tracks these dependencies automatically and recompiles units only when necessary.
Circular Unit References
When units reference each other directly or indirectly, the units are said to be mutually dependent. Mutual dependencies are allowed as long as there are no circular paths connecting the uses clause of one interface section to the uses clause of another. In other words, starting from the interface section of a unit, it must never be possible to return to that unit by following references through interface sections of other units. For a pattern of mutual dependencies to be valid, each circular reference path must lead through the uses clause of at least one implementation section.
In the simplest case of two mutually dependent units, this means that the units cannot list each other in their interface uses clauses. So the following example leads to a compilation error:
However, the two units can legally reference each other if one of the references is moved to the implementation section:
To reduce the chance of circular references, it’s a good idea to list units in the implementation uses clause whenever possible. Only when identifiers from another unit are used in the interface section is it necessary to list that unit in the interface uses clause.