2. События
Список событий для объекта, на которые он реагирует, можно посмотреть в Инспекторе Объектов на странице События (см. рис.1).
Событие – это то, что происходит во время выполнения программы. Каждое событие имеет имя. Например, щелчок кнопки “мыши” – событие OnClick, создание Формы – OnCreate. Наиболее часто применяемые события представлены в таблице 1.
Для создания обработчика события программисту необходимо раскрыть список компонентов в верхней части окна Инспектора Объектов и выбрать необходимый компонент. Затем, на странице События Инспектора Объектов, нажатием левой клавиши мыши выбрать название обработчика и дважды щелкнуть по его правой (белой) части. В ответ Lazarus активизирует окно Редактора Кода модуля и покажет заготовку процедуры обработки выбранного события. Для каждого обрабатываемого события в тексте модуля организуется процедура (procedure), между ключевыми словами begin и end которой программист на языке Object Pascal записывает требуемый алгоритм обработки события.
Часто применяемые события
Описание события
Возникает при активизации Формы
Возникает при создании Формы. В обработчике данного события следует задавать действия, которые должны происходить в момент создания Формы, например установка начальных значений
Возникает при нажатии кнопки мыши в области компонента.
Возникает при двойном нажатии кнопки мыши в области компонента
Возникает при нажатии клавиши на клавиатуре. Параметр Key имеет тип Char и содержит ASCII-код нажатой клавиши (клавиша Enter клавиатуры имеет код #13, клавиша Esc — #27 и т.д.). Обычно это событие используется в том случае, когда необходима реакция на нажатие одной из клавиш
Возникает при нажатии клавиши на клавиатуре. Обработчик этого события получает информацию о нажатой клавише и состоянии клавиш Shift, Alt и Ctrl, а также о нажатой кнопке мыши
Структурные операторы
В языке Pascal имеются две реализации одной из основных алгоритмических структур – ветвления – условный оператор (if) и оператор выбора (case).
1. Условный оператор if…then…else
Условный оператор if служит для организации процесса вычислений в зависимости от какого-либо логического условия.
Оператор if может принимать две формы записи (полную и короткую):
if <условие> then <оператор1> else <оператор2>;
if <условие> then <оператор>;
Оператор условия if выполняется следующим образом. Сначала вычисляется выражение, записанное в условии. В результате его вычисления получается значение булевского типа. В первом случае, если значение выражения есть True (истина), выполняется <оператор1>, указанный после слова then. Если результат вычисления выражения в условии есть False (ложь), то выполняется <оператор2>. Во втором случае — если результат выражения Тгuе, выполняется <оператор>, если False — выполняется оператор, следующий сразу за оператором if. По правилам каждая из ветвей может содержать либо один выполняемый оператор, либо несколько, объединенных в составной оператор. Точка с запятой перед else не ставится.
Операторы if могут быть вложенными. Формат записи:
if <условие1> then
if <условие2> then <оператор1>
При вложениях всегда действует правило: служебное слово else всегда связывается с ближайшим по тексту служебным словом if, которое еще не связано со служебным словом else.
Event order
Lazarus offers various events that you can use to enter your own procedures to handle things that happen in your application (e.g. a user clicks a button).
There are rather a lot of possible events to cater for a lot of different scenarios. Somebody who does not know Lazarus or Delphi could well pick the wrong event.
Lazarus documentation
The Lazarus tutorial has some information on what events do what.
Forms
Typical event order for forms is:
Form.OnCreate
This is the equivalent to the class constructor in forms. Use this to initialize form-level variables etc. The form is not yet shown at this time.
Form.OnShow
When the form is shown (e.g. when loading the form or setting its .Visible property to true), this event is fired — just before the form is visible. This allows you to modify the visual appearance of controls (e.g. disable certain controls) without flickering.
Form.OnActivate
This occurs after Form.Show.
At the OnActivate stage controls instantiated in OnCreate are present and correct, and should have the minimum needed properties set (such as Parent) plus anything else OnCreate specified.
OnActivate signals that this form now has focus, so mouse/key events will start arriving.
Form.OnDeactivate
Fired after the form loses focus.
Note: Switching between different applications in the OS will not cause either Form.OnActivate or Form.OnDeactivate to fire. Thus Form.OnActivate/Form.OnDeactivate only track different forms changing focus within an application.
To track whether the Application itself receives or loses focus, use Application.OnActivate and Application.OnDeactivate.
Form.OnDestroy
The equivalent to a class destructor in forms. Use this to clean up/free variables.
When the main form of an application is destroyed, the application terminates.
General controls
These events apply to various controls. Please use the Object Inspector to check if it is available for the control you’re currently using.
OnEditingDone
The OnEditingDone event for controls can act like the Validate event in other programming languages: it indicates the user is done changing the control and intends to keep that value. The program can now check the control content for correctness, show error messages, update database fields, etc.
Note: As soon as you click outside the control (even on a control that cannot receive focus) OnEditingDone is triggered.
(See TControl.MouseDown procedure, introduced in r11778).
Applicable Delphi information
Because the implementation of events in Lazarus and Delphi is similar, a lot of Delphi-related documentation is applicable to Lazarus with minor modifications.
Delphi documentation is often handy. You can search for the actual control you want to know more about to get a list of its events.
Lazarus какие события возникают при открытии формы
Lazarus offers various events that you can use to enter your own procedures to handle things that happen in your application (e.g. a user clicks a button).
There are rather a lot of possible events to cater for a lot of different scenarios. Somebody who does not know Lazarus or Delphi could well pick the wrong event.
Lazarus documentation
The Lazarus tutorial has some information on what events do what.
Forms
Typical event order for forms is:
Form.OnCreate
This is the equivalent to the class constructor in forms. Use this to initialize form-level variables etc. The form is not yet shown at this time.
Form.OnShow
When the form is shown (e.g. when loading the form or setting its .Visible property to true), this event is fired — just before the form is visible. This allows you to modify the visual appearance of controls (e.g. disable certain controls) without flickering.
Form.OnActivate
This occurs after Form.Show.
At the OnActivate stage controls instantiated in OnCreate are present and correct, and should have the minimum needed properties set (such as Parent) plus anything else OnCreate specified.
OnActivate signals that this form now has focus, so mouse/key events will start arriving.
Form.OnDeactivate
Fired after the form loses focus.
Note: Switching between different applications in the OS will not cause either Form.OnActivate or Form.OnDeactivate to fire. Thus Form.OnActivate/Form.OnDeactivate only track different forms changing focus within an application.
To track whether the Application itself receives or loses focus, use Application.OnActivate and Application.OnDeactivate.
Form.OnDestroy
The equivalent to a class destructor in forms. Use this to clean up/free variables.
When the main form of an application is destroyed, the application terminates.
General controls
These events apply to various controls. Please use the Object Inspector to check if it is available for the control you’re currently using.
OnEditingDone
The OnEditingDone event for controls can act like the Validate event in other programming languages: it indicates the user is done changing the control and intends to keep that value. The program can now check the control content for correctness, show error messages, update database fields, etc.
Note: As soon as you click outside the control (even on a control that cannot receive focus) OnEditingDone is triggered.
(See TControl.MouseDown procedure, introduced in r11778).
Applicable Delphi information
Because the implementation of events in Lazarus and Delphi is similar, a lot of Delphi-related documentation is applicable to Lazarus with minor modifications.
Delphi documentation is often handy. You can search for the actual control you want to know more about to get a list of its events.
Lazarus какие события возникают при открытии формы


- biMinimize — кнопка минимизации окна;
- biMaximize — кнопка максимизации окна.
Любой из этих кнопок можно присвоить значение False — недоступна.
- bsDialog — рамка диалоговой панели;
- bsSingle — тонкая рамка;
- bsNone — без рамки;
- bsSizeToolWindow — инструментальная панель Windows с изменяемыми размерами;
- bsToolWindow — инструментальная панель.
- poDesigned — форма при запуске приложения будет находиться в том положении на экране, как она находится в конструкторе Delphi;
- poDefault — форма при запуске может оказаться в любом месте экрана;
- poScreenCenter -форма при запуске находится в центре экрана.
- wsNormal — приложение имеет нормальные размеры;
- wsMaximized — приложение развернуто на весь экран;
- wsMinimized — приложение свернуто.

Далее создадим еще одно событие — onMouseMove. Это событие отслеживает перемещение курсора мыши на форме. Событие будет заключаться в следующем: при перемещении мыши на форме, в заголовке формы будут отображаться координаты положения мыши. Текст вставляемый в процедуру должен быть таким:
caption:= ‘X:’+IntToStr(x) +’ Y:’+ IntToStr(y);
(IntToStr — функция преобразующая числовой целый тип к строке, т.к. заголовок окна имеет тип String. X и Y — координаты курсора мыши (тип Integer), они передаются в процедуру как параметр).
70: Lazarus — Обработка событий
Обработчики событий. Создание обработчика события. События для основных компонентов. Примеры создания процедур обработки событий.
Компонент Form1 – событие OnCreate. Компонент Form1 – событие OnActivate.
Компонент Edit – событие OnKeyPress. Компонент Edit – событие OnChange. Компонент Edit – событие OnClick.
Компонент Button – событие OnClick.
События мыши и клавиатуры.. События мыши. События клавиатуры. Распознавание нажатых клавиш.