Sign in Join
Wiki copytemporary

Lazarus Tutorial/it

Deutsch · English · Español · Français · Italiano · Magyar · Nederlands · Português · Shqip · Slovenčina · Suomi · Македонски · Русский · 中文(中国) · 中文(台灣) · 日本語

This is the start of a Lazarus Tutorial. Please feel free to add your experiences to it.

Panoramica

Lazarus è un strumento di sviluppo libero per il compilatore Free Pascal, anche esso gratis e open source. L'IDE Lazarus (screenshot) è uno stabile e ricco ambiente di sviluppo per la creazione di applicazioni grafiche e da console. Lazarus attualmente funziona su GNU/Linux, Mac OS X e Win 32 e fornisce un editor di codice personalizzabile ed un ambiente visuale per la creazione di form che include un package manager, un debugger ed una GUI completa, integrata con il compilatore Free Pascal.

Si inizia - Il tuo primo programma in Lazarus!

Scarica, installa ed esegui Lazarus con il quale sarà disponibile il compilatore FreePascal. Diverse finestre compariranno sul desktop. Il menù principale in alto, L'Object Inspector sulla sinistra, l'editor sorgente di Lazarus che occupa gran parte del desktop ed una finestra Form1 già pronta che invece occupa l'editor sorgente.

Nella finestra del menù in alto, sotto la linea del menù c'è una riga di tab. Se la tab 'Standard' non è ancora selezionata, selezionala cliccandoci con il mouse. Quindi cerca l'icona del pulsante (un rettangolo con la scritta 'OK') e cliccaci con il mouse. Quindi clicca sulla finestra Form1, in un punto qualsiasi a sinistra a partire dal centro. Un rettangolo ombreggiato con il nome "Button1" comparirà. Clicca ancora sul pulsante nella Standard tab quindi clicca ancora nel Form1 a destra dal centro: comparirà un rettangolo con il nome 'Button2'.

Ora clicca sul pulsante Button1 per selezionarlo. L'Object Inspector visualizzerà le proprietà dell'oggetto Button1. Vicino in alto c'è una proprietà che si chiama 'Caption' con visualizzato il valore 'Button1'. Clicca su questo riquadro e cambia 'Button1' con 'Press'. Se premi Enter o click in un altro riquadro, vedrai l'etichetta del primo pulsante su Form1 cambiato in 'Press'. Ora clicca sulla Events tab sull'Object Inspector per vedere i vari eventi che sono associati al pulsante. Questi includono OnClick, OnEnter, OnExit etc. Seleziona il riquadro a destra di OnClick: una piccolo pulsante con tre puntini compariranno. Clicca su questo. Sarai reindirizzato automaticamente sull'editor di codice e il cursore sarà collocato nel mezzo. Modifica il codice come segue:

pascal
procedure TForm1.Button1Click(Sender: TObject);
 begin
   {now type:}    Button1.caption := 'Press again';
   {the editor has already completed the procedure with}
 end;

Premi F12 per selezionare la finestra Form1 anzichè l'editor di codice. Ora modifica le proprietà di Button2: clicca su Button2 per visualizzare le sue proprietà nel Object Inspector. Cambia la proprietà Caption 'Exit' al posto di 'Button2'. Ora seleziona la tab degli eventi e clicca sul riquadro OnClick. Clicca su .... . Dopo verrai reindirizzato all'interno dell'editor di codice all'interno di un altra procedura. Modifica il codice come segue:

pascal
 procedure TForm1.Button2Click(Sender: TObject);
 begin
 {now type:}   Close;
 {the editor has already completed the procedure with} 
 end;

Premi F12 per vedere la finestra Form1 di nuovo. Sei pronto per compilare ora: Il modo più semplice per farlo è selezionare 'Esegui' dal menù principale in alto con l'opzione run che si trova nel sotto-menù. In alternativa potresti semplicemente premere F9. Questo prima eseguirà la compilazione e dopo (se è andato tutto bene) il link, quindi eseguirà il tuo programma.

Diverse finestre di testo appariranno e diversi tipi di messaggi verranno visualizzati, infine la tua finestra Form1 riapparirà ma senza la griglia di punti. Questa è la finestra principale della tua applicazione e sta aspettando che premi i pulsanti oppure che ci interagisci.

Prova cliccando sul pulsante 'Press'. Noterai che questo cambia in 'Press again'. Ora clicca sul pulsante 'Exit'. La finestra si chiuderà ed il programma cesserà di funzionare. La finestra orginale Form1 con la griglia di punti riapparirà, pronta ad accettare altre attività di modifica.

Puoi salvare il tuo lavoro ora selezionando Project > Save Project As > il tuo file .pas selezionato.

Seconda sessione

Apri nuovamente il progetto che hai salvato. Sulla finestra Form1 clicca sul pulsante 'Press' (Button1) per selezionarlo. Seleziona la tab 'Events' sull'Object Inspector, clicca sul riquadro a destra dopo OnClick, clicca sui puntini (…), per ritornare sul punto esatto dell'editor sorgente.

Modifica il codice come segue:

procedure TForm1.Button1Click(Sender: TObject);

pascal
{Makes use of the Tag property, setting it to either 0 or 1}
 begin
   if Button1.tag = 0 then
   begin
     Button1.caption := 'Press again';
     Button1.tag := 1
   end else
   begin
     Button1.caption := 'Press';
     Button1.tag := 0
   end
 end;

Salva il tuo lavoro, ricompila ed esegui. Il pulsante sinistro ora cambierà in due messaggi alternati.

Il resto spetta a te!

Se preferisci scrivere programmi console o text-based (per esempio se stai seguendo un corso di base di programmazione Pascal, o hai bisogno di scrivere programmi per l'uso in modalità batch o per programmazione di sistema), è possibile comunque utilizzare Lazarus per modificare, compilare ed eseguire i tuoi programmi. Diventa un ambiente ideale per lo sviluppo in Pascal. Guarda Console Mode Pascal.

L'Editor

Quando si esegue Lazarus per la prima volta, appariranno sul proprio desk-top una serie di finestre autonome separate o fluttuanti.

La prima, in esecuzione sulla parte superiore del desk-top, è intitolata Lazarus Editor vXXXXXX - project1 (che verrà successivamente modificata per riflettere il nome del proprio progetto attualmente aperto). Questa è la finestra principale di controllo del proprio progetto e contiene il menù principale e la Component Palette (NdT: schede dei componenti).

Sulla riga sotto la barra del titolo c'è il Menù Principale con le consuete voci per File, Modifica, Cerca, Vista funzioni e così via, ed alcune selezioni che sono specifiche di Lazarus. Sotto a questo a sinistra c'è un gruppo di BitButtons (che permettono un accesso rapido a particolari opzioni del Menù Principale) e sulla destra c'è la Component Palette.

Sotto la finestra dell'Editor di Lazarus apparirà sulla sinistra la finestra dell' Object Inspector e sulla destra il Lazarus Source Editor. Ci può essere un'altra finestra più piccola, intitolata Form1, sopra alla finestra del Lazarus Source Editor. Se non è visibile direttamente, può venire visualizzata premendo il tasto F12, che scambia la vista tra il Source Editor e la Form. La finestra della Form è quella su cui si costruirà l'interfaccia grafica della propria applicazione, mentre il Source Editor è la finestra che mostra il codice Pascal associato all'applicazione che si sta sviluppando. Il funzionamento dell'Object Inspector è discusso in maggiore dettaglio più avanti, durante la descrizione della Component Palette.

Quando si inizia un nuovo progetto (o all'esecuzione iniziale di Lazarus) verrà costruita una Form predefinita, composta di uno spazio nel quale c'è una griglia di punti che facilita il posizionamento dei componenti della form e una barra nella parte superiore che contiene i consueti pulsanti Minimizza, Massimizza e Chiudi. Se si clicca con il cursore del mouse su qualsiasi parte di questo spazio, si vedranno le proprietà di questa form elencate sull'Object Inspector a sinistra del desk-top.

Altre finestre che potrebbero divenire visibili durante l'utilizzo: il Project Inspector, che contiene il dettaglio dei file inclusi nel proprio progetto, e permette di aggiungere file o di cancellarli dal proprio progetto; la finestra Messaggi, che mostra i messaggi del compilatore, gli errori o i rapporti di sviluppo del proprio progetto; se Lazarus viene eseguito da una finestra di terminale, tale finestra rimane visibile ed anche in essa si vedranno i messaggi del compilatore.

Il Menù Principale

For a detailed description of every menu item which is accessible from the Lazarus IDE Main Menu, please refer to the Main menu/it page.

The Button bar

A small toolbar area on the left of the main editor window, just below the Main Menu and to the left of the Component Palette, contains a set of buttons which replicate frequently-used Main Menu selections:

New unit, Open (with a down-arrow to display a drop-down list of recently used files), Save, Save all, New Form, Toggle Form/Unit (ie show either form or source code of Unit), View Units, View Forms, Run (ie compile and Run), Pause, Step Into, Step over (the last two are Debugger functions).

The Component Palette

A Tabbed toolbar which displays a large number of icons representing commonly used components for building Forms.

Each tab causes the display of a different set of icons, representing a functional group of components. The left-most icon in each tabbed group is an obliquely leftward-facing arrow, called the Selection Tool.

If you allow the mouse cursor to hover over any of the icons on the Component Palette, without clicking on the icon, the title of that component will pop-up. Note that each title begins with a 'T' - this signifies 'Type' or more accurately 'Class' of the component. When you select a component for inclusion in a form, the Class is added to the type section of the interface part of the Unit (usually as part of the overall TForm1), and an instance of that class is added to the var section (usually as the variable Form1). Any Methods that you design to be used by the Form or its Components (ie Procedures or Functions) will be placed in the implementation part of the Unit

In the following list of the Components, you will find links to files that contain descriptions of the Units in which they are found. If you want to find out about the properties of a particular component, it is often worth looking at the Inheritance of that component and then inspecting the properties of the base type from which it is derived. For example, to understand TMaskEdit it is also useful to examine TCustomMaskEdit.

TABS (the names are largely self-explanatory):

Frequently used components: TMainMenu, TPopupMenu, TButton, TLabel, TEdit, TMemo, TToggleBox, TCheckBox, TRadioButton, TListBox, TComboBox, TScrollBar, TGroupBox, TRadioGroup, TCheckGroup, TPanel, TActionList

More, often-used components: TBitBtn, TSpeedButton, TStaticText, TImage, TShape, TBevel, TPaintBox, TNotebook, TLabeledEdit, TSplitter, TTrayIcon, TMaskEdit, TCheckListBox, TScrollBox, TApplicationProperties, TStringGrid, TDrawGrid, TPairSplitter, TColorBox, TColorListBox, TChart

TTrackBar, TProgressBar, TTreeView, TListView, TStatusBar, TToolBar, TUpDown, TPageControl, TTabControl, THeaderControl, TImageList, TPopupNotifier

TOpenDialog, TSaveDialog, TSelectDirectoryDialog, TColorDialog, TFontDialog, TFindDialog, TReplaceDialog, TOpenPictureDialog, TSavePictureDialog, TCalendarDialog, TCalculatorDialog, TPrinterSetupDialog, TPrintDialog, TPageSetupDialog

Several useful Dialog procedures or functions don't appear on the Palette, but are easily used as direct calls from your source program.

For several good examples of the use of Components see the $LazarusPath/lazarus/examples subdirectory of your source installation. Many of the programs show how to use dialogs and other components directly without using the IDE and component palette or having a separate form definition file: all the components are fully and explicitly defined in the main Pascal program. Other example programs make full use of the IDE.

Some examples don't work straight away: you may need to play about with paths and permissions of files or directories. If you want to compile any of the examples, make sure that you have read/write/execute permissions for the files and directories, or copy the files to a directory where you do have the appropriate permissions.

Try running the 'testall' program to see a menu of the available components together with small example test forms for most of them; then inspect the code to find out how they work!

TColorButton, TSpinEdit, TFloatSpinEdit, TArrow, TCalendar, TEditButton, TFileNameEdit, TDirectoryEdit, TDateEdit, TCalcEdit, TFileListBox, TXMLPropStorage, TIniPropStorage, TBarChart, TButtonPanel, TIDEDialogLayoutStorage

Data-aware components, which largely replicate the Standard and Additional groups but are applicable to Databases: TDBNavigator, TDBText, TDBEdit, TDBMemo, TDBImage, TDBListBox, TDBComboBox, TDBCheckBox, TDBRadioGroup, TDBCalendar, TDBGroupBox, TDBGrid

TDatasource, TMemDataset, TSdfDataSet, TFixedFormatDataSet, TDbf

TTimer, TIdleTimer, TLazComponentQueue, THtmlHelpDatabase, THtmlBrowserHelpViewer, TProcessUTF8, TAsyncProcess, TProcess, TSimpleIPCClient, TSimpleIPCServer, TXMLConfig, TEventLog

A group of components to help interfacing with other languages and software tools. SynEdit is an advanced multi-line edit control, for Borland Delphi, Kylix and C++Builder. It supports Syntax Highlighting and code completion, and includes exporters for html, tex and rtf. It is a full-VCL/CLX control, meaning it is not a wrapper for Microsoft Windows controls, and no run-time library is required; this make SynEdit a crossplatform component. Compatibility with FreePascal is also planned, and SynEdit is the edit component in Lazarus IDE. see synedit at sourceforge. : TSynEdit, TSynAutoComplete, TSynExporterHTML, TSynMacroRecorder, TSynMemo, TSynPasSyn, TSynFreePascalSyn, TSynCppSyn, TSynJavaSyn, TSynPerlSyn, TSynHTMLSyn, TSynXMLSyn, TSynLFMSyn, TSynUNIXShellScriptSyn, TSynCssSyn, TSynPHPSyn, TSynTeXSyn, TSynSQLSyn, TSynPythonSyn, TSynVBSyn, TSynAnySyn, TSynMultiSyn

How To Use the Palette

To use the Palette, there must be an open form on view in the editor (if there isn't one, select File -> New Form). Click on the icon in the appropriate tab of the Palette for the component you want to use, then click on the Form, near where you want the component to appear. When the desired component appears, you can select it by clicking with the mouse, then move it to the exact place on the Form where you want it and adjust its size. Adjustments can be made to the appearance either by altering the picture itself on the Form using the mouse, or by changing the relevant Property in the Object Editor for that component.

If you install additional components, either those you have written yourself, or some coming as a package from some other source, then extra tabs with the relevant icons will appear in your Component Palette. These new components can be selected and used on your forms in the same way as those supplied by default.

How to use Standard Controls, Common Controls and Extended Controls

The Units StdCtrls, ComCtrls and ExtCtrls contain definitions and descriptions of many of the most commonly used controls for constructing Forms and other Objects in Lazarus Applications.

Many of the final target controls that the application developer wants to use, such as TButton, TMemo, TScrollBar etc, have a corresponding ancestor class such as TCustomButton, TCustomMemo or TCustomScrollBar. Several of the properties and methods relevant to the final target control are defined (and explained) more fully in the TCustomXXX class, and are inherited by the final target control.

If you drop a component on the form editor you don't need to add code explicitly to create it. The component is automatically created by the IDE together with the form, and destroyed when the form is destroyed.

However, if you create the component yourself by code don't forget to free it when it is no longer needed.

If you place a component on the Form Designer and look at the Object Inspector, you can observe the properties change as you move the component around.

For example, if you place a button (TButton) on the form, click on it to select it, then move it around the form with the mouse, you can watch the values of Top and Left change in the Object Inspector to reflect the new position. If you use the object's re-sizing bars to adjust its size, you can watch the Height and Width properties change as well.

On the other hand, by using the Object Inspector, you can select the value associated with a property such as height, and type in a new value; you can watch the size of the object on the form change to reflect the new value.

You can also explicitly change the properties of the object in code by typing (in the appropriate Implementation section of the Source editor), for example

pascal
         Form1.Button1.Height := 48;

If you type this new value into the Source Editor and then look back at the Form Designer, you will see that the button on the Form has taken the new size. The new value will also be shown in the Object Inspector.

In summary, there are usually about three different ways to determine each property of an object:

The components defined in these Units have several properties that are common to most of them, and other properties that are specific to the individual components. We shall describe the most common ones here. Unusual or control-specific properties will be described for the individual controls.

Additional Help can always be obtained by selecting a property or keyword, in either the Object Inspector or the Source Editor, and pressing F1. You will be taken by your Help browser to the appropriate page in the documentation.

If the description of a property on that page is insufficient, you can navigate to the corresponding description in the ancestor classes, by selecting the links in the Inheritance listing or by selecting the ancestor Type in the declaration of the object.

text
           <i>Constructors</i>

such as ``Create`` allocate memory and system resources needed by the object. They also call the constructor of any sub-objects present in the class.

text
           <i>Destructors:</i>

remove the object and de-allocate memory and other resources. If you call ``Destroy`` for an object which hasn't being initialized yet it will generate an error. Always use the ``Free`` method to deallocate objects, because it checks whether an object's value is ``nil`` before invoking ``Destroy``.

Take the following precautions when creating your own Destroy method:

text
           <caption><b>Some commonly listed properties</b></caption>

Property

Meaning

Action

The main action or event associated with the object. For example selecting an 'Exit' Button might cause the 'Close' action

Align

Defines the way in which an object is to be lined up with the parent object. Possible values are alTop (placed at the top and using the full available width), alBottom, alLeft (placed at the left and using the full available height), alRight. alNone (place anywhere on parent control) or alClient (takes all available space next to controls aligned to top, bottom, left or right)

Anchor

Used to keep a control a certain distance from the defined edges of a parent control, when the parent is resized. For example [akBottom, akRight] will keep the control a fixed distance from the bottom right corner.

AutoSelect

When True, an editing control will select all its text when it receives focus or when the Enter key is pressed.

AutoSelected

True indicate that the edit or combobox control has just performed an AutoSelect operation so that subsequent mouse-clicks and keystrokes proceed normally without selecting the text.

BorderSpacing

The space around the edge between an Anchored control and its parent.

Caption

The text that is displayed on or near the control; it should preferably give some clue as to the function of the control, or an instruction such as 'Close' or 'Execute'. By default Caption is set to be the same as the 'Name' property, and the application programmer should substitute meaningful text instead of the default values.

CharCase

Indicates how text is displayed in a text editing control: Normal (retaining the case of the letters typed by the user), converted to uppercase, or converted to lowercase

Constraints

Sets the minimum and maximum sizes for a control. If a control is resized the new dimensions are always within the ranges given here. You should take care when setting these options that they do not conflict with the Anchors and Align settings.

Color

The Colour to be used to draw the control or to write the text it contains.

Enabled

A Boolean property to determine whether or not a control is capable of being selected and performing an action. If it is not Enabled, it is often Grayed out on the Form.

Font

The Font to be used for writing the text associated with the control - either the caption or label, or the text-strings contained within the control. The entry on the Object Inspector usually has a (+) box on the left, and selecting this box reveals further options such as character set, colour and size.

Hint

A short piece of informative pop-up text that appears if the mouse-cursor hovers over the control.

Items

The list of 'Things' that the object contains, such as a group of images, a series of lines of text, a number of actions in an actionlist, etc

Lines

An array of strings, containing the textual data in controls with more than a single line of data, such as an Edit-Box or a Combo-Box. The array is zero-indexed, ie the lines are numbered [0..numLines-1]

Name

The identifier by which the control is known in the program. The IDE gives it a default name based on the underlying type, for example successive instances of TBitButton would be named Form1.BitBitton1 and Form1.BitButton2; it is up to the application programmer to give them more meaningful names such as ExitButton or OKButton. By default the Name of the control is applied to the Caption for the control, but the text of the Caption may be changed separately.

PopUpMenu

A window containing context-sensitive menu information that pops up when the right mouse button is clicked on the object.

Position (or Top, Left)

Determines where the control is located on the parent form or window

ReadOnly

Boolean property which, if True, signifies that the contents of the control can be read by the user or the calling routine, but cannot be written or changed.

ShowHint

Allows a small window containing a context-sensitive Help or other description to be displayed when the mouse cursor 'hovers' over the control.

Size (or Height and Width)

The dimensions of the control

Style

The options available for Style depend upon the sort of Control being considered: for instance the Style may be defined by TFormStyle, TBorderStyle, TButtonStyle etc.

TabOrder

Integer defining where in the sequence of tabs on the Form this control is to lie

TabStop

Boolean property which if True places this control in the sequence of objects that the user can reach by successively pressing the Tab key

Text

The String of Text that represents the actual data that this control contains. Applies particularly to Text, Memo and StringList types of object. Most of the editing operations (such as Select, Clear, Cut, Copy) are performed in this part of the object, which holds the actual string being edited. If the control contains more than a single line of text, for example TMemo or TComboBox, then the textual elements are arranged as an array of strings (zero-indexed, ie numbered from [0..numLines-1]) in Lines.

Visible

If true, the object can be seen on the Form; if False, object is hidden

WordWrap

Logical flag to show whether or not word-wrap is enabled, ie if a word comes close to the end of a line and is going to be too long for the line, it is wrapped down to the next line.

Many actions are commonly listed in the 'Events' tab of the Object Inspector. If you select an entry in the list, a ComboBox appears with a DropDown list showing any actions that have aleady been defined, and allowing you to choose one to be associated with this event. Alternatively you can select the ellipsis (three dots ...) and you will be taken to an area of the Source Editor where you can begin typing your own action instructions for the selected event.

While a large number of events is available for any given control, in practice it is only necessary to populate a few of them. For most controls, it is sufficient to provide coding for 'OnClick'; for more complex controls it may be necessary also to provide for 'OnEntry' (when the mouse cursor enters the Control and gives it focus) and 'OnExit' (when the mouse cursor leaves the Control; or you may need to write an event handler for 'OnChange' or 'OnScroll', depending on the nature of the particular control with which you are dealing.

The pop-up menu that appears when you right-click an object in the Form Designer has, as its first item: 'Create default event' and selecting this option will have the same effect as selecting the ellipsis in the Object Inspector for the default event, usually OnClick: you are taken to the Implementation area of the Source Editor where you can type the code for the event handler.

A common strategy in Object-Oriented programming is to provide an ActionList with the facility for entering, removing or editing a number of pre-defined actions from which the most appropriate can be selected to use in any particular instance.

text
           <caption><b>Some commonly listed Actions</b></caption>

Action

Meaning

OnChange

Action to be taken if any change is detected (eg mouse move, mouse click, key press, edit text, alter picture, etc)

OnClick

Action to be taken when the (left) mouse button is clicked. This is usually the main or default action of the control; for example clicking on a button or checkbox initiates the action associated with the checkbox. It may alternatively initate a process of selection, for instance in a TextBox or Memo, or signal the beginning of painting with a Pen or Brush.

Click

A method to emulate in code the effect of clicking on a control. This method is most often found in Button-type controls (TButton, TBitBtn, TSpeedButton etc). A procedure can be written that calls the same code as the OnClick action. This facility can be particularly useful if the activation of one control by clicking causes a cascade of other controls to be activated, and the Click method can be used to initiate the action rather than having the user explicitly click on a lot of controls.

OnDragDrop

Action to be taken during Drag-Drop manoeuvres, ie when the mouse is used to 'capture' an item or some text etc and move it around the screen to a new location.

OnEntry

Action to be taken when the mouse cursor enters the area occupied by the object, usually transfering focus to that object. This might include changes in the appearance of the object such as highlighting or raising the border.

OnExit

Action to be taken when the mouse moves out of the area of the object, usually transferring focus out of the object.

OnKeyPress

Action to be taken for any key-press. Subtly different from OnKeyDown, which simply responds to a key being down, whether or not it was already down when focus was given to this control. OnKeyPress requires that a key becomes pressed while focus is in this control.

OnKeyDown

Action to be taken if a key is down while focus is in this control. Subtly different from OnKeyPress - for example the key might already have been down when focus entered this control, whereas OnKeyPress requires the key to become pressed while focus is in the control.

On Key Up

Action to be taken if a key is up (ie not pressed) while focus is in this control.

OnMouseMove

On Mouse Down - Action to be taken if the mouse cursor moves while focus is in this control.

OnMouseDown

Action to be taken if the mouse button is down while focus is in this control.

OnMouseUp

Action to be taken if the mouse button is up while the cursor is over this control. Implies that the mouse button was previously down and has been released. The case where the cursor enters the control but the mouse button has not yet been pressed is covered by OnEntry or OnMouseEnter.

OnResize

Action to be taken when the control is resized. Might include re-alignment of text or selection of a different font size etc.

How to use Menus

Hints for creating Menus for your Forms

TMainMenu is the Main Menu that appears at the top of most forms; form designers can customise by choosing various menu items. TPopupMenu is a menu window that pops up with pertinent, usually context-sensitive, details and choices when the right mouse button is clicked near a control

Main Menu is a non-visible component : that is, if the icon is selected from the Component Palette and placed on the Form, it will not appear at Run-time. Instead, a Menu bar with a structure defined by the Menu Editor will appear. Popup menus, placed on the form by selecting the icon from the Component Palette, do not appear at all unless the right mouse button is clicked on a control that owns such a menu.

To see the Menu Editor, right-click on the Main Menu or Popup Menu icon on your Form. A pop-up box appears, that invites you to enter items into the Menu bar.

An Edit box is displayed, containing a Button labelled New Item1. If you right-click on that box, a pop-up menu is displayed that allows you to add a new item before or after (along the same level) or create a sub-menu with the opportunity to add further items below (or above) the new item in a downward column.

Any or all of the MenuItems that you add can be configured using the Object Inspector.

At the least you should give each item a Caption which will appear on the Menu Bar (you may also wish to give it a more meaningful Name). The caption should indicate the activity to be selected, such as "File Open" or "Close", "Run" or "Quit"

If you want a particular letter in the Caption to be associated with a shortcut key, that letter should be preceded by an ampersand. The Menu item at run-time will appear with the shortcut letter underlined, and hitting that letter key will have the same effect as selecting the menu item. Alternatively you can choose a shortcut key sequence (such as Ctrl-C for Copy or Ctrl-V for Paste - the standard Keyboard shortcuts) with the ShortCut property of the MenuItem.

It is often helpful to use the Menu controls in conjuction with an ActionList which contains a series of standard or customised Actions. Menu Items can be linked in the Object Inspector to Actions on the list, and the same actions can be linked to Buttons, ToolBar Buttons, SpeedButtons etc. It is obviously economic of effort to re-use the same code to respond to the various events, rather than writing separate OnClick event handlers for each individual control.

By default a number of standard actions is pre-loaded from StdActns or, if DataAware controls are being used, from DBActns, and these can be chosen using the ActionList editor which appears when you right-click on the ActionList icon on the Form Designer.

The Debugger

Still to be written.

see also :category: IDE Window - Debug

The Lazarus files

text
   (Thanks to Kevin Whitefoot.)
   (Additions by Giuseppe Ridinò, User:Kirkpatc and Tom Lisjac)

When you save you will actually be saving two files:

text
  xxx.pas and yyy.lpr

(You save more than that but those are the ones you get to name). The project file (lpr) and the unit file (pas) must not have the same name because Lazarus will helpfully rename the unit (inside the source code) to the same as the unit file name and the program to the name of the project file (it needs to do this or the compiler will probably not be able to find the unit later when referred to in the project file). Of course to be consistent it changes all the occurrences of unit1 to xxx.

So if you are saving a project called again, trying to save again.pas and again.lpr fails because unit names and program names are in the same name space resulting in a duplicate name error.

So here is what I ended up with:

e:/lazarus/kj/lazhello:

text
total 4740  free 76500
-rwxrwxrwx   1 kjwh     root  4618697 Mar 24 11:19 again.exe
-rw-rw-rw-   1 kjwh     root     3002 Mar 24 11:21 again.lpi
-rw-rw-rw-   1 kjwh     root      190 Mar 24 11:18 again.lpr
-rw-rw-rw-   1 kjwh     root      506 Mar 24 11:08 againu.lfm
-rw-rw-rw-   1 kjwh     root      679 Mar 24 11:08 againu.lrs
-rw-rw-rw-   1 kjwh     root      677 Mar 24 11:08 againu.pas
-rw-rw-rw-   1 kjwh     root     2124 Mar 24 11:08 againu.ppu
-rwxrwxrwx   1 kjwh     root      335 Mar 24 11:07 ppas.bat

Note that there are many more files than the two that I thought I was saving.

Here is a brief note about each file:

again.exe: The main program binary executable. Win32 adds an "exe" extension. Linux has none (just the name of the program). This file will be huge in Linux due to the inclusion of debugging symbols. Run the "strip" utility to remove them and substantially shrink the executable size.

again.lpi: (Lazarus Project Information). This is the main information file of a Lazarus project; the equivalent Delphi main file of an application will be the .dpr file. It is stored in an XML format and contains instructions about all the libraries and units required to build the executable file.

again.lpr: The main program source file or master file. Despite its lazarus specific extension it is in fact a perfectly normal Pascal source file. It has a uses clause that lets the compiler find all the units it needs. Note that the program statement does not have to name the program the same as the file name. This file is usually fairly small, with just a few statements to initialise, build the forms, run and close the application. Most of the work is done in the unit source files, with suffix '.pas'

againu.lfm: This is where Lazarus stores the layout of the form unit, in human readable form. It reflects the properties of the various components, as set in the Object Inspector. Each object description starts with a line:

pascal
object xxxx 
  then there follows a list of properties 
  (including embedded or nested objects) then an 
end

line. Lazarus uses this file to generate a resource file (.lrs) that is included in the initialisation section of the againu.pas unit. Delphi dfm files can be converted to lfm format in the Lazarus IDE using the Tools->Convert DFM file to LFM utility.

againu.lrs: This is the generated resource file which contains the instructions to the program for building the form (if you look in the main Unit file, you will see in the initialization section the line

text
{$i againu.lrs}

which instructs the program to load the resource file). Note that it is not a Windows resource file.

againu.pas: The unit that contains the code for the form; this is usually the only file that the application programmer needs to edit or inspect, and contains any code specifically supplied by the programmer (especially event handlers).

againu.ppu: This is the compiled unit which gets linked into the executable file together with any other units named in the Uses section.

ppas.bat: This is a simple script that links the program to produce the executable. If compilation is successfull, it is deleted by the compiler.

Original contributors and changes

This page has been imported from the epikwiki version.


Lazarus IDE Tools


From the Free Pascal wiki, page "Lazarus Tutorial/it", as it stood on 2021-12-08 after a change by Kupferstecher, out of the wiki's dump of 2024-05-26. Copyright stays with the author who wrote it, according to the old wiki's Licensing page. If you have concerns about this material, message the admin.

Revision 3, last changed by WikiArchive .

Talk about this page

Nobody has opened a bench for this page yet. Sign in to open one.