Как создать вторую форму в лазарусе

от admin

Form Tutorial

The form (class TForm) represents a window or dialog box that is the user interface of an application. It is the container on which all other components (e.g. buttons, labels, edit fields, images, etc.) are inserted .

The First GUI Application

Upon successfully installing Lazarus and starting a new Application Project, an empty form is created. Otherwise you can create a new GUI application under Main menu -> Project -> New Project -> Application OK.

Now you have created a new, fully functional project with a form:

To run the newly created project, you can simply press the F9 key or click with the mouse on the main menu icon Start.png (or Main menu: Run -> Run). The project will be compiled and executed.

Nothing really exciting happens. The form (Form1) changes slightly in appearance and the points from the raster grid (help for positioning of individual components) disappear (as long as the grid points are visible, you also know that it is still in design mode):
Form1 Designmodus.png -> Form1 Runmodus.png

Next, you can place a TButton onto the form. This will be used later to allow the opening of a second form:

Select the TButton from the Standard tab on the Component Palette.

and click on the form: There is now a button placed on Form1 with the name and caption «Button1».

In order for this button to do something, you have to announce that you intend to do something when you click it. This can be regarded as a simple event. For this you need an event handler that is called after the click. The event handler for a mouse click can be quite easily reached by double-clicking on Button1 (or in the Object Inspector, select Button1 -> Events tab -> OnClick, then click on the [. ] button). This creates a procedure TForm1.Button1Click in the code editor, which is always called (at runtime, not in design time) when Button1 is clicked:

NeuesProjekt2.png

To make the application do something after clicking on Button1, add some code between the Begin and End of the procedure TForm1.Button1Click like this:

Now run the form by pressing F9 , and notice that when the button is clicked the form caption and the button caption both change.

You can now experiment a little bit and learn how to use the standard components. To get started, I would recommend you to try samples of the following components:

There is additional helpful information in the Lazarus Tutorial.

The Use of a Second Form

The tutorial shows how to use multiple forms in a project. In this example, only two forms, Form1 (main form) and Form2, are created, but the process is identical for additional forms.

There is a main form with a button, which when clicked opens the new form. The new form also receives a button which when clicked closes the new form and returns you to the main form.

If you have worked through the first tutorial The first GUI app, you will need to delete the code between the begin and end of procedure TForm1.Button1Click. Otherwise you will need to create a new project (application), drop a button on the form, and create the OnClick event handler for this Button1.
Click the new button to enter a caption (visible text on the button). To do this, select the button (just click it once) and in the Object Inspector click Properties -> Caption, and enter the text «Open Form2».

Objektinspektor.png

In the Main menu click File -> New Form, to add a second form (Form2) to the project. Place a button (Button1) on Form2 and create the OnClick event handler for it. Change the caption of this button to «Close».

Now the project has two forms, each of which can be selected and displayed with Main menu Project -> Forms (or key combination ⇧ Shift + F12 ). Alternatively, you can select the tab for a Unit in the Source Editor, then use F12 to switch between the code editor and form designer for the form of the associated Unit.

In the source code editor, go to the Form1 associated Unit (Unit1) and add «Unit2» to the Uses clause:

Now you can call Unit2 (and thus Form2) from Unit1.

Next, edit the OnClick event of the button belonging to Form1:

Now you can start the project (Start.png or F9 ) and open Form2 by clicking the button on Form1.

Difference between Show and ShowModal

Both methods Show and ShowModal make a form visible. To see the difference between Show and ShowModal:

  • Extend the previous example The use of a second form by adding a second TButton to Form1.
  • Select Button1 and change the properties Name to btnShow and Caption to Show.
  • Select Button2 and change the properties Name to btnShowModal and Caption to ShowModal.
  • Create (or modify) the OnClick event handler of the two buttons as follows:
  • Start and watch the difference!

This procedure makes a form visible and continues to execute the code of the calling control (Form1). In our example, the message (ShowMessage) appears almost simultaneously with Form2. You can also continue to use the calling form Form1. For example, it is possible to move it, or click the Show button again (but clicking ShowModal will cause an error).

Instead of using <myForm>.Show; , it is also possible to use <myForm>.Visible:=True; . The method Show does the following:

The only difference between <myForm>.Show; , and <myForm>.Visible:=True; is that the form displayed using Show will be on top of all other forms currently displayed.

ShowModal halts the processing of code in the calling control (Form1) until the newly opened form (Form2) has been closed. In the example, the ShowMessage line immediately following ShowModal is executed only after Form2 is closed. The calling form is frozen: You can neither move Form1 nor click any of its buttons.

ShowModal is a function that returns an integer result, see TModalResult. The returned value allows branching based on how the form was closed.

Two Forms That Can Call Each Other

It is generally good program design to avoid calling the main form from a second form. It is better to return to the main form by closing the second form (as in the previous example) and letting focus revert to the main form. It is, however, possible to call the main from from a sub-form, as this example will show.

In order for Form1 to call Form2, Unit1 must have Unit2 in its Uses clause. Conversely, for Form2 to call Form1, Unit2 must have Unit1 in its Uses clause. This leads to a potential Circular Unit Reference compiler error, with each Unit referring to the other. This example also shows how to avoid the Circular Unit Reference error.

To set up this example, either modify the forms from the previous example (The Use of a Second Form), or create a new project with two forms, each having a single button. Set the caption of Form1.Button1 to «Open Form2», and set the caption of Form2.Button1 to «Open Form1».

If you are modifying the previous example, remove «Unit2» from the Uses clause in Unit1.

Add a Uses clause to the Implementation section of each Unit. Add Unit2 to the Unit1 clause, and add Unit1 to the Unit2 clause, as below:

Now change the code located behind the OnClick event of the button event handler:

Passing Variables to Other Forms

In accordance with the above example The Use of a Second Form, it is possible to declare a global variable in the interface part of Unit2. This would allow access in both Unit1 and Unit2 to one and the same variable (This is because by putting Unit2 in the Uses clause of Unit1, all variables declared in the interface part of Unit2 are also available in Unit1). This practice should be limited to a minimum, as it quickly becomes difficult to remember which individual variables are in scope, potentially increasing errors. It is better to use local variables, define a Property in a Class or, alternatively, as a variable in a class.

In the next project, a second form is opened by clicking on the button. In this case, in the unit of the main form is counted how often the second shape has been shown. In this second form you can ask to see by clicking on the button, how often it has been opened:

  • a new project with two forms, each a button on it and their OnClick events to evaluate.
  • now, in the public part of the Class TForm2 (Unit2) a variable (in this case a constant, which we defined as variable abuse) of type integer with the name Count create:
  • now even customize the Button event handler accordingly:

In this way you can in Unit1 access all public variables/properties/functions/procedures (general methods) of Unit2.

Other Form-Related Subjects

Use Another Form as the Main Form

If you determine after a while that you want to have displayed rather a different form or new form for the view at startup, you can under the main menu Project -> Project Options -> Forms:

Projekteinstellungen Formulare.png

Alternatively, you can display, in Mainmenu -> Project -> Show .lpr file, that Project.lpr (Pascal code of the main program) and create the first form to be displayed as the first:

Save properties of the shape at end of program

Generate the form dynamically

Create a Lazarus designed form dynamically

You do not have to create all the forms that may be called during the term of an application at startup. Some developers generally keep none of it and delete the code automatically created when you insert a new form in a project from the Projekt.lpr out immediately. If you want to write a library that contains a couple of GUIs, you can not get around the dynamic creation of forms.

  • new application with two forms, Form1 a button (add «Unit2» in the uses clause of unit1)
  • open the Projekt.lpr (Project -> lpr file.)
  • delete the line «Application.CreateForm(TForm2, Form2);»
  • in the OnClick event of Button1, Form1 add following code:
  • now simply start

Creating a new form dynamically

The following example will demonstrate how new forms can be generated in code, without using the Form Designer,.

In this example clicking a button should open another form that itself contains a button. Clicking this second button makes a message appear warning that the form will close; then the form is closed.

Как создать вторую форму в лазарусе

The form (class TForm) represents a window or dialog box that is the user interface of an application. It is the container on which all other components (e.g. buttons, labels, edit fields, images, etc.) are inserted .

The First GUI Application

Upon successfully installing Lazarus and starting a new Application Project, an empty form is created. Otherwise you can create a new GUI application under Main menu -> Project -> New Project -> Application OK.

Now you have created a new, fully functional project with a form:

Form1 Designmodus.png

To run the newly created project, you can simply press the F9 key or click with the mouse on the main menu icon Start.png(or Main menu: Run -> Run). The project will be compiled and executed.

Nothing really exciting happens. The form (Form1) changes slightly in appearance and the points from the raster grid (help for positioning of individual components) disappear (as long as the grid points are visible, you also know that it is still in design mode):
Form1 Designmodus.png-> Form1 Runmodus.png

Next, you can place a TButton onto the form. This will be used later to allow the opening of a second form:

Select the TButton from the Standard tab on the Component Palette.

and click on the form: There is now a button placed on Form1 with the name and caption «Button1».

In order for this button to do something, you have to announce that you intend to do something when you click it. This can be regarded as a simple event. For this you need an event handler that is called after the click. The event handler for a mouse click can be quite easily reached by double-clicking on Button1 (or in the Object Inspector, select Button1 -> Events tab -> OnClick, then click on the [. ] button). This creates a procedure TForm1.Button1Click in the code editor, which is always called (at runtime, not in design time) when Button1 is clicked:

NeuesProjekt2.png

To make the application do something after clicking on Button1, add some code between the Begin and End of the procedure TForm1.Button1Click like this:

Now run the form by pressing F9 , and notice that when the button is clicked the form caption and the button caption both change.

You can now experiment a little bit and learn how to use the standard components. To get started, I would recommend you to try samples of the following components:

There is additional helpful information in the Lazarus Tutorial.

The Use of a Second Form

The tutorial shows how to use multiple forms in a project. In this example, only two forms, Form1 (main form) and Form2, are created, but the process is identical for additional forms.

There is a main form with a button, which when clicked opens the new form. The new form also receives a button which when clicked closes the new form and returns you to the main form.

If you have worked through the first tutorial The first GUI app, you will need to delete the code between the begin and end of procedure TForm1.Button1Click. Otherwise you will need to create a new project (application), drop a button on the form, and create the OnClick event handler for this Button1.
Click the new button to enter a caption (visible text on the button). To do this, select the button (just click it once) and in the Object Inspector click Properties -> Caption, and enter the text «Open Form2».

Читать:
Как записать слово в переменную в c

Objektinspektor.png

In the Main menu click File -> New Form, to add a second form (Form2) to the project. Place a button (Button1) on Form2 and create the OnClick event handler for it. Change the caption of this button to «Close».

Now the project has two forms, each of which can be selected and displayed with Main menu Project -> Forms (or key combination ⇧ Shift + F12 ). Alternatively, you can select the tab for a Unit in the Source Editor, then use F12 to switch between the code editor and form designer for the form of the associated Unit.

In the source code editor, go to the Form1 associated Unit (Unit1) and add «Unit2» to the Uses clause:

Now you can call Unit2 (and thus Form2) from Unit1.

Next, edit the OnClick event of the button belonging to Form1:

Now you can start the project ( Start.pngor F9 ) and open Form2 by clicking the button on Form1.

Difference between Show and ShowModal

Both methods Show and ShowModal make a form visible. To see the difference between Show and ShowModal:

  • Extend the previous example The use of a second form by adding a second TButton to Form1.
  • Select Button1 and change the properties Name to btnShow and Caption to Show.
  • Select Button2 and change the properties Name to btnShowModal and Caption to ShowModal.
  • Create (or modify) the OnClick event handler of the two buttons as follows:
  • Start and watch the difference!

This procedure makes a form visible and continues to execute the code of the calling control (Form1). In our example, the message (ShowMessage) appears almost simultaneously with Form2. You can also continue to use the calling form Form1. For example, it is possible to move it, or click the Show button again (but clicking ShowModal will cause an error).

Instead of using <myForm>.Show; , it is also possible to use <myForm>.Visible:=True; . The method Show does the following:

The only difference between <myForm>.Show; , and <myForm>.Visible:=True; is that the form displayed using Show will be on top of all other forms currently displayed.

ShowModal halts the processing of code in the calling control (Form1) until the newly opened form (Form2) has been closed. In the example, the ShowMessage line immediately following ShowModal is executed only after Form2 is closed. The calling form is frozen: You can neither move Form1 nor click any of its buttons.

ShowModal is a function that returns an integer result, see TModalResult. The returned value allows branching based on how the form was closed.

Two Forms That Can Call Each Other

It is generally good program design to avoid calling the main form from a second form. It is better to return to the main form by closing the second form (as in the previous example) and letting focus revert to the main form. It is, however, possible to call the main from from a sub-form, as this example will show.

In order for Form1 to call Form2, Unit1 must have Unit2 in its Uses clause. Conversely, for Form2 to call Form1, Unit2 must have Unit1 in its Uses clause. This leads to a potential Circular Unit Reference compiler error, with each Unit referring to the other. This example also shows how to avoid the Circular Unit Reference error.

To set up this example, either modify the forms from the previous example (The Use of a Second Form), or create a new project with two forms, each having a single button. Set the caption of Form1.Button1 to «Open Form2», and set the caption of Form2.Button1 to «Open Form1».

If you are modifying the previous example, remove «Unit2» from the Uses clause in Unit1.

Add a Uses clause to the Implementation section of each Unit. Add Unit2 to the Unit1 clause, and add Unit1 to the Unit2 clause, as below:

Now change the code located behind the OnClick event of the button event handler:

Passing Variables to Other Forms

In accordance with the above example The Use of a Second Form, it is possible to declare a global variable in the interface part of Unit2. This would allow access in both Unit1 and Unit2 to one and the same variable (This is because by putting Unit2 in the Uses clause of Unit1, all variables declared in the interface part of Unit2 are also available in Unit1). This practice should be limited to a minimum, as it quickly becomes difficult to remember which individual variables are in scope, potentially increasing errors. It is better to use local variables, define a Property in a Class or, alternatively, as a variable in a class.

In the next project, a second form is opened by clicking on the button. In this case, in the unit of the main form is counted how often the second shape has been shown. In this second form you can ask to see by clicking on the button, how often it has been opened:

  • a new project with two forms, each a button on it and their OnClick events to evaluate.
  • now, in the public part of the Class TForm2 (Unit2) a variable (in this case a constant, which we defined as variable abuse) of type integer with the name Count create:
  • now even customize the Button event handler accordingly:

In this way you can in Unit1 access all public variables/properties/functions/procedures (general methods) of Unit2.

Other Form-Related Subjects

Use Another Form as the Main Form

If you determine after a while that you want to have displayed rather a different form or new form for the view at startup, you can under the main menu Project -> Project Options -> Forms:

Projekteinstellungen Formulare.png

Alternatively, you can display, in Mainmenu -> Project -> Show .lpr file, that Project.lpr (Pascal code of the main program) and create the first form to be displayed as the first:

Save properties of the shape at end of program

Generate the form dynamically

Create a Lazarus designed form dynamically

You do not have to create all the forms that may be called during the term of an application at startup. Some developers generally keep none of it and delete the code automatically created when you insert a new form in a project from the Projekt.lpr out immediately. If you want to write a library that contains a couple of GUIs, you can not get around the dynamic creation of forms.

  • new application with two forms, Form1 a button (add «Unit2» in the uses clause of unit1)
  • open the Projekt.lpr (Project -> lpr file.)
  • delete the line «Application.CreateForm(TForm2, Form2);»
  • in the OnClick event of Button1, Form1 add following code:
  • now simply start
Creating a new form dynamically

The following example will demonstrate how new forms can be generated in code, without using the Form Designer,.

In this example clicking a button should open another form that itself contains a button. Clicking this second button makes a message appear warning that the form will close; then the form is closed.

Как создать вторую форму в лазарусе

Внимание Скидка 50% на курсы! Спешите подать
заявку

Профессиональной переподготовки 30 курсов от 6900 руб.

Курсы для всех от 3000 руб. от 1500 руб.

Повышение квалификации 36 курсов от 1500 руб.

Лицензия №037267 от 17.03.2016 г.
выдана департаментом образования г. Москвы

Конспект урока на тему «РАБОТА С ФОРМАМИ В LAZARUS»

Муниципальное образовательное учреждение

дополнительного образования детей центр дополнительного образования детей

«Сланцевский центр информационных технологий»

Занятие по программе «Программирование в Lazarus » на тему «Работа с формами в Lazarus » Кочергиной Кристины Николаевны, педагога дополнительного образования

Тема «Работа с формами в Lazarus »

создать ситуацию для развития умения «слушать — делать – понимать»;

научить учащихся получению инструментальных знаний через привитие навыков использования компьютера для разрешения учебной ситуации;

образовательная : знакомство со средой Lazarus : компоненты, свойства, события, методы; овладение навыком работы с программой; познакомить с понятием переменных, изучить типы данных и их совместимость. Познакомится с основными арифметическими операциями и функциями;

развивающая : повышение интереса к процессу программирования в информатике; развитие познавательного интереса, логического мышления, речи и внимания учащихся, формирование информационной культуры и потребности приобретения знаний;

воспитательная : привитие учащимся навыка самостоятельности в работе, воспитание трудолюбия, чувства уважения к науке.

Тип занятия: занятие совершенствования знаний, умений и навыков, целевого применения усвоенного.

Вид занятия: комбинированный урок-практикум.

На этом занятии мы научимся создавать приложения, в которых используются несколько форм.

Кроме того мы изучим новый компонент TRadioGroup для создания групп переключателей.

Научимся применять условный оператор для анализа состояния переключателей.

Форма является объектом, отсутствующим на палитре компонентов. Чтобы добавить новую форму в проект, нужно выбрать команду Файл → Создать форму или щелкнуть кнопку Создать форму на панели инструментов.

Появится новая пустая форма. Называться она будет Form2, а соответствующий ей файл с исходными текстами добавиться в Редактор кода на новую вкладку Unit2.

После добавления новой формы, проект нужно сохранить.

Каждую форму, включаемую в приложение, необходимо, прежде всего, создать описанным способом. Создание формы не означает ее немедленного отображения, а только выделение и инициализацию памяти для нее. Все формы создаются неявно при запуске приложения, но отображается автоматически только главная форма, а остальные остаются скрытыми. Впоследствии их можно отобразить вызовом метода Show , например:

Если же требуется отобразить окно как модальное, то есть так, чтобы, не закрыв его, пользователь не мог переключиться на другое окно этого же приложения, то вместо метода Show следует использовать метод ShowModal:

Окна, открытые с помощью методов Show и ShowModal , можно вновь скрыть при помощи метода Hide :

Форма окна, скрытого методом Hide, не уничтожается, и это окно в любой момент можно снова отобразить. Все объекты форм уничтожаются (освобождают память) автоматически при завершении работы приложения.

Основные методы формы:

Close — закрывает форму;

Hide — форма становится невидимой;

Show — показать форму;

ShowModal — показать форму в модальном режиме. Когда форма показана в модальном режиме, приложение не может выполняться, пока форма не будет закрыта.

Т.е. для показа форм можно использовать один из двух методов: Show или ShowModal. Метод Show предназначен для показа формы в обычном окне, а ShowModal — для показа формы в модальном окне.

Различие между этими двумя видами окон состоит в том, что между обычными окнами можно перемещаться произвольным способом, а перейти в другое окно из модального окна можно только после его закрытия.

Модальные окна хорошо подходят для задания всевозможных настроек, выполнения ввода промежуточных значений, отображения результатов.

Теперь у нас есть все необходимые знания, для того чтобы создать приложение с несколькими формами.

Проект «Три формы»

Задание. Создать приложение с тремя формами: Главная, Опции и О программе. Форму Опции вызывать в обычном окне. Для вызова формы О программе использовать модальное окно.

На рисунке показаны главная форма и подформы нашего нового проекта.

Ход выполнения проекта

Создайте новое приложение, сохраните файлы проекта в папке « Okna ».

Разместите на форме Form1 3 кнопки, измените свойства объектов в соответствии с таблицей.

Приложение типа VCL Forms Application в Delphi. Приложение типа Application в Lazarus

Если в системе Delphi создать приложение типа VCL Forms Application , то программа будет состоять из следующих частей:

  • главный модуль программы;
  • модули, которые подключаются к основной программе.
1.1. Главный модуль *.dpr

При создании приложения, главный модуль программы помещается в файле с расширением *.dpr и имеет следующий код

Как видно из вышеприведенного кода, к главному модулю подключается дополнительный модуль с помощью строки

  • Unit1 – название модуля в программе;
  • Unit1.pas – название файла, в котором описывается код модуля Unit1 .

При создании приложений, использующих интерфейс Windows, этот код менять не нужно. Он корректируется автоматически системой Delphi при добавлении в программу новых файлов модулей.

Например, после добавления второй формы с именем Unit2 , которая размещается в файле Unit2.pas , раздел uses будет иметь вид

Также автоматически будет добавлена новая строка в раздел операторов

1.2. Дополнительные модули. Структура

В приложениях типа VCL Forms Application каждый содержательный элемент программы, обычно формируется в отдельный модуль (файл). Содержательным элементом может быть, например, форма или отдельный файл с набором (библиотекой) функций и тому подобное.
В наиболее общем случае, структура любого модуля добавляется, следующая

1.3. Пример структуры приложения типа VCL Forms Application . Рисунок

На рисунке 1 изображена структура приложения типа VCL Forms Application . Рассматривается случай с подключенными двумя модулями с именами Unit1 , Unit2 .

Delphi. Структура приложения типа VCL Forms Application

Рисунок 1. Приложение VCL Forms Application . Случай с двумя подключенными формами, которые размещены в файлах Unit1.pas и Unit2.pas

2. Структура приложения типа Application в системе Lazarus

В системе Lazarus есть возможность создавать приложения, которые поддерживают интерфейс Windows и обеспечивают кроссплатформеннисть. Это приложения типа Application. В приложениях типа Application системы Lazarus структура программы подобна структуре Windows-приложений системы Delphi и состоит из следующих основных частей:

  • главный файл проекта *.lpr (Lazarus Project Main Source)
  • дополнительные модули ( unit ), подключаемые к главному файла проекта.
2.1. Главный файл проекта *.lpr

Главный файл проекта имеет следующий вид

В процессе создания приложения в системе Lazarus этот файл не нужно корректировать, он корректируется автоматически при добавлении (удалении) дополнительных частей в программе. Это могут быть новые формы, файлы модулей с библиотеками функций и тому подобное.

2.2. Файлы дополнительных модулей

В системе Lazarus составляющая файла дополнительных модулей такая же как в системе Delphi.

Модули имеют два основных раздела:

  • interface — здесь объявляются общедоступные компоненты модуля;
  • implementation — здесь объявляются скрытые компоненты модуля и непосредственно реализация.
2.3. Пример структуры для приложения типа Application. Рисунок

На рисунке 2 изображена структура приложения типа Application в системе Lazarus, которое имеет одну главную форму и один дополнительный модуль.

Lazarus. Структура приложения типа Applicaiton

Рисунок 2. Структура приложения типа Applicaiton в системе Lazarus

Стрелкой показано подключение в разделе uses модуля Unit1 , который соответствует главной форме программы и размещается в файле Unit1.pas . Если нужно подключить второй модуль, то в разделе uses этот модуль дописывается к предыдущим модулям через запятую.

Похожие статьи