Getting Started With Lazarus

December 9, 2016 | Author: Liviu | Category: N/A
Share Embed Donate


Short Description

Lazarus is a Delphi compatible cross-platform IDE for Free Pascal. It includes LCL which is more or less compatible with...

Description

Getting Started with Lazarus

About Lazarus Project History Lazarus was started in February of 1999. It was primarily founded by three individuals:   

Cliff Baeseman Shane Miller Michael A. Hess

All three had attempted to get involved with the Megido project which dissolved. In frustration they started the Lazarus project. It has had a steady growth of supporters and developers during the following years. The founders are not involved with the project any more. The next oldest member of the team is Marc Weustink. He got involved with the project in Aug. 1999. Following him is Mattias Gaertner who got involved in Sept. 2000. Both of them

have been the major contributors to the core of what makes Lazarus tick. More about the history in the Wiki

So just what is Lazarus? Lazarus is a Delphi compatible cross-platform IDE for Free Pascal. It includes LCL which is more or less compatible with Delphi's VCL. Free Pascal is a GPL'ed compiler that runs on Linux, Win32, OS/2, 68K and more. Free Pascal is designed to be able to understand and compile Delphi syntax, which is OOP. Lazarus is the part of the missing puzzle that will allow you to develop Delphi like programs in all of the above platforms. Unlike Java which strives to be a write once run anywhere, Lazarus and Free Pascal strives for write once compile anywhere. Since the exact same compiler is available on all of the above platforms it means you don't need to do any recoding to produce identical products for different platforms.

Yeah, but what about the GUI? What widget set are you using? That is the neat part. You decide. Lazarus is being developed to be totally and completely API independent. Once you write your code you just link it against the API widget set of your choice. If you want to use GTK+, great! If you want it to be Gnome compliant, great! As long as the interface code for the widget set you want to use is available you can link to it. If it isn't available, well you can write it. For example. Let's say you are creating a product on Windows using the standard Windows widgets. Now you want to create a Linux version. First you decide what widget set you want to use. Let's assume you want to use gtk+. So you copy the code over to your Linux development machine, compile, and link against the gtk+ interface unit. That's it. You've now just created a Linux version of the Windows product without any additional coding. At this point in the development we are using Win32, gtk2+, Carbon and QT as our API widget set. Bindings for custom drawn components are in the works and other widget sets are planned, too.

So is this thing really RAD like Delphi? It sure is. Is it totally completed? No not yet.The overall IDE is complete and can be used for most programming needs. Several aspects of the project are still in need of help. Hint. Hint.

Can I use my existing Delphi code? Some of it yes. If the code is standard Delphi pascal and it uses the standard components found in Delphi then the answer is yes. If it uses some specific database, OCX, or DCU then the answer would be no. These items are specific to Windows and would only work on and within Windows. However, if you are only looking to create a Windows product using Free

Pascal and Lazarus then the answer would be yes. This hasn't been added to the LCL yet but it should be possible in the future.

Can I create commercial products with this? Yes. The code for the Free Pascal compiler is licensed under the GPL. This means that it is open source, free, whatever name you want to stick to it. You can modify the code if you wish but you MUST distribute those changes or make them available to others if they wish to use it. The FCL (Free Pascal Component Libraries) and the LCL (which will eventually become part of the FCL) are licensed under a modified LGPL. In a nut shell this means that you can write your own proprietary software that just links to these libraries. You can sell your application without the need to supply or make available your code. However, as with the compiler if you make modifications to the FCL or LCL you must make those changes available to the general public and the world.

I give up, where did the name come from? One of the original projects that made an attempt to build a Delphi clone was Megido. However this effort died. Lazarus as you know was the biblical figure that was raised from the dead by Christ. Soooooo. The project is named Lazarus as it was started/raised from the death of Megido.

Introduction The following topics will help you to download and install Lazarus, and then use it to write a simple "Hello World" program. You are also given advice about how to experiment to find out more about Pascal and Lazarus. You will type your programs into the Lazarus editor or copy them from the Programs or Tutorials sections of the site. At a single click of a button, Lazarus will run the program in its editor. It will translate the programs into machine code instructions that are executed by the computer. Lazarus will provide information about any errors in the program if it is unable to translate it. We hope you will agree that Lazarus is a great example of free software. Click on the first topic title below, to continue: 1. Downloading Lazarus How to download Lazarus from the web onto your PC 2. Writing your First Pascal Program using Lazarus How to write your first Pascal program using Lazarus 3. Experimenting with Lazarus Suggested experiments to learn more about Pascal and Lazarus. 4. Copying a Pascal Program into Lazarus How copy a Pascal program (e.g. from this site) into Lazarus

Downloading Lazarus Before doing this exercise you must   

check the requirements (Windows 32-bits, memory, operating system, disk storage); obtain permission from the PC owner; consider whether to take a backup of all important material on the PC.

The following steps describe how to download Lazarus to your PC. 1. Start your Internet browser and go to http://sourceforge.net/projects/lazarus/files/ 2. Read the installation requirements and ensure that your PC satisfies those requirements before continuing. The downloaded file has a size of about 135 MB but you will need about 2 GB of space on your hard drive for the files (including all of the examples) after installation. 3. To download Lazarus, click on the link with text "lazarus-1.6.0-fpc-3.0.0-win64.exe (134.8 MB)". (This is the recommended version on 28th February 2016). If necessary, download the 119.9 MB 32-bit lazarus-1.6.0-fpc-3.0.0-win32.exe from here. What happens next depends on what browser and operating system you are using. Follow your normal procedure for downloading a file, and make note of where you download the file to. The next step is to install Lazarus. The next topic describes how to do that.

Writing your First Pascal Program using Lazarus Before doing this exercise you must first have Lazarus installed on your PC. Now we will use the newly installed Lazarus to create a simple program and run it. The programming culture demands that the first program written in any language should output "Hello World!" to the screen. The steps to do this are as follows:

1. Start Lazarus by double-clicking on its Launch icon button.

, or by using the Start

After Lazarus has started, you will see the following menu bar:

2. On the menu bar click on Project. 'Project' is circled in purple in the graphic above. A drop-down menu will appear:

3. On the drop-down menu, click on New Project .... The Create a new project dialogue appears:

4. Click on Program in the list of options, as shown above, and then click on the OK button. If you are using a very recent version of Lazarus you should click on Simple Program instead and you will not see the unnecessary code before begin (making Step 16 redundant). You may see the following Project changed dialogue:

5. If do see the above Project changed dialogue, just click on the No button. (It was a brand new project and so nothing valuable will be lost). If you do not see the above dialogue you do not need to do anything in this step. You should now be able to see a new project in the Source Editor

6. Save the file in a suitable folder as 'HelloWorld' by selecting menu item Project > Save Project As... The name on the first line of the program should change to HelloWorld. 7. Click to the right of 'begin' to place the cursor (a vertical bar) after 'begin'. 8. Press the Return key once (to go onto a new empty line), and carefully type "writeln('Hello World!');" 9. Press the Return key again, and carefully type "readln;" The program should now look like this:

10. Carefully check that every character is correct. Especially check that the single quotes and the semi-colons are there. 11. The time has come to compile and run the program! Press the green triangle the top left of the Lazarus menu bar, OR press the F9 key.

near

In case you were wondering, the file will be saved automatically, so you do not need to save it first. After a small delay, you should see a mainly black window appear:

12. If it did not work, you will need to check again for errors, and correct them before clicking on the run icon again. a. Carefully check that every character is correct. b. Especially check that the single quotes and the semicolons are there. 13. If it did work, there are a few things for you to notice: The green start icon has now changed to grey , indicating that the program is still running, and that consequently the icon is inactive. There is a blinking white cursor (a horizontal bar) on the black window, indicating that the program is awaiting input (due to the readln; statement). 14. Press the Return key again, to make the program terminate. The Execution stopped dialogue appears:

15. Press the OK button. The dialogue disappears and Lazarus is ready for further instructions from you. 16. Delete the lines between the first line and begin. The program should now look like this:

17. Confirm that the program runs as before. For simple programs running in Windows this is all that you really need. 18. If you can think of anything we could have made more straightforward for you, then please let us know. If it did not work, then please tell us what went wrong. Features introduced:    

New console program opened Program named Text denoted by single quotes Text output to screen

If you want to, you can quit from Lazarus by selecting menu item File > Quit Alternatively, you can move on to the next topic in this guide.

Installing Lazarus Before doing this exercise you must have downloaded Lazarus onto your PC. How to do this is described in the previous topic. Make sure that you have permission to install the software on the PC. If you are not an experienced PC user, it would be a good idea to obtain the help of someone who is experienced at installing software. The following steps describe how to install Lazarus to your PC. 1. Log onto your PC. You may need to use an admin account in order to install software. 2. Start Windows Explorer and navigate to the folder to which you downloaded the Lazarus zip file. Typically, you may have downloaded it to the My Documents/Downloads folder. The setup file may appear as follows:

3. Start the installation by double-clicking on the Lazarus Setup icon. 4. Follow the on-screen instructions. Accept the default answers (e.g. install to where it suggests, and use the standard installation, not the advanced one). After Lazarus has finished installing, you will be ready for the next exercise. The next step is to write your first Pascal Program, using Lazarus. The next topic describes how to do this.

Experimenting with Lazarus You must have Lazarus installed on your PC to carry out this exercise. Also, you should have written the "Hello World" program, using Lazarus. The following steps describe experiments you can do to learn more about Pascal and Lazarus.

1. If it is not already running, start Lazarus by double-clicking on its Launch Icon , or by using the Start button. 2. If your "Hello World" program is not already loaded in the editor, open it by using the menu option File > Open ... and navigate to the folder you saved it in. 3. Use the mouse to select HelloWorld.lpi (note that the extension is .lpi) and click on the button Open. 4. Click OK to confirm that you want to open the project. You should see the HelloWorld program in the editor. 5. Press the Run icon to run the program.

near the top left of the Lazarus menu bar, OR press the F9 key

After a small delay, you should see a mainly black window appear and at the top, it should say...

6. Take a look at the Run icon, and you will see that it is no longer green: The triangle is now grey 7. Press the little red square running.

. This signifies that the program is running. (with tooltip Stop) to stop the program

This is very useful if a program gets stuck in a loop for some unknown reason. The familiar Execution stopped dialogue appears. Press the OK button to continue. 8. There are several ways to stop a running program: o o o o

Press the little red square (with tooltip Stop), as we have just seen. Click the Lazarus toolbar to ensure it has focus, then press Ctrl+F2. On the console window, click the X at the top right. On the console window, right click the icon at the top left, and select menu item Close.

Click the green triangle to run the program again and experiment with the various ways of stopping the program. 9. The purpose of the readln; line at the end of the program is to prevent the black window from disappearing as soon as the rest of the program has finished. Try commenting out the readln; statement by typing // at the start of the line, so the line becomes //readln;. Then click on the green Run icon. Anything on a line after // is treated as a comment to help programmers and is not converted to machine code. The black window will disappear before you can see what has been output to it. 10. In the editor, remove the //. Notice that the tab at the top left of the editor now says *HelloWorld. The asterisk signifies that the program code has changed since it was last saved. The Save icon on the toolbar also changes from grey to its active state, again indicating that there are unsaved changes. 11. Click on the Save icon to save the changes you have just made. Note that the asterisk has gone, and the save icon is now in its inactive (grey) state. Tip: Computers can crash at any time, so always remember to save your work frequently! 12. Run the program again. With the readln; back in action, the console window will not vanish, as before, but will wait for your input. Press the Enter key to allow the program to end. 13. In the editor, change writeln to WRITELN and run the program again. Pascal is not case sensitive, so the program still runs as it did before. 14. In the editor, change WRITELN to write and run the program again. Notice that the cursor is now positioned at the end of Hello World!. The writeln instruction performed this write instruction then positioned the cursor at the start of the following line. 15. Amend the program to: a. Output “Hello” b. Position the cursor at the start of a new line 16. Save the program as Hello. (Accept the default file extension .lpi). 17. Run the program to test it.

Features introduced:    

Various ways of stopping a program Use of readln to prevent application window from disappearing Use of comment characters // to comment out the rest of a line Presence of asterisk to signify that unsaved changes have been made to the code.

Copying a Pascal Program into Lazarus 1. Start Lazarus by double-clicking on its Launch icon button.

, or by using the Start

After Lazarus has started, you will see the following menu bar:

2. On the menu bar click on Project. 'Project' is circled in purple in the graphic above. A drop-down menu will appear:

3. On the drop-down menu, click on New Project .... The Create a new project dialogue appears:

4. Click on Program in the list of options, as shown above, and then click on the OK button. You may see the following Project changed dialogue:

5. If do see the above Project changed dialogue, just click on the No button. (It was a brand new project and so nothing valuable will be lost). If you do not see the above dialogue you do not need to do anything in this step. You should now be able to see a new project in the Source Editor

6. In your browser, navigate to the page containing the Pascal program you want to copy. 7. Copy the code into the clipboard by selecting it then pressing CTRL+C, as follows: a. Use the mouse to position the cursor before the 'p' of 'program' in the first line b. Drag the cursor with the left mouse button down until the cursor is positioned just after the final full stop after 'end.' c. Press CTRL+C 8. In Lazarus, select all the text in the editor. 9. Press CTRL+V to replace all of this text with the copied Pascal code. 10. Carefully check that all the Pascal code is now in the Lazarus editor. Check that there are neither extra, nor missing characters at the beginning and end. 11. Save the file by selecting menu item Project > Save Project As... 12. Navigate to a suitably named new folder and save the file with the name given in the first line of the program. The program is now available for you to edit and run. Remember that student programs may require some adjustment before they will compile and run successfully. (We have tested all of them, but sometimes changes to compilers necessitate minor alterations to the original code). Experiment with the program. See what improvements you can make. If you want to, you can quit from Lazarus by selecting menu item File > Quit

Common Error Checklists for Lazarus and Delphi There are several types of error, with consequences ranging from deficiencies in the formatting of the output to the calculation of wrong results. A compilation error (which prevents the compiler from compiling the source code) is usually a syntax error but could be an error in the compiler itself. A syntax error results when the source code does not obey the rules of the language. The compiler generates error messages to help the programmer to fix the code. The source code may compile to machine code which then fails upon execution. A run-time error causes this situation. Potentially the most serious type of error occurs when the program appears to be working but is performing faulty processing due to logic errors in the source code. We classify the common errors as syntax errors, run-time errors, and logic errors, but begin with three very common errors for beginners that do not fit neatly into any of these categories.

Common miscellaneous errors Description of error File not saved

Outcome

Comment

Error message in Delphi: Could not create output file

Save the file with a meaningful name before writing code.

Error message in Lazarus: Error while linking Readln; statement missing Console window closes

Put a readln; statement immediately before the final end.

Real number output in Format of real number scientific notation (a minor not user-friendly. deficiency if not actually an error)

Give the field width and number of decimal places e.g. writeln(radius : 6 : 2);

Common syntax errors Do not be discouraged if your first programs generate many error messages. Often there are cascading errors, in which a single mistake such as a misspelled identifier in a variable declaration gives rise to several error messages. You then make one correction and several messages disappear at once. In the following table showing extracts from error messages to look out for, note how some messages are much more helpful than others. Description of error

Typical message content in Delphi

Typical message content in Lazarus

Comment

Description of error

Typical message content in Delphi

Typical message content in Lazarus

Comment

Misspelled identifier

Undeclared identifier Identifier not found

Spelling of identifier must be consistent

Previous statement not separated by semicolon

Missing operator or semicolon

Error indicated on the line following the missing semicolon

";" expected but …

Tip: The error message is not always on the line with the error, so remember to look at adjacent nearby lines as well. Semicolon immediately before else

';' not allowed before ";" expected but 'ELSE' "ELSE" found

Use of = instead of := '=' expected but ':=' for simple assignment found e.g.

Illegal expression

The if … then … else is one statement and should not have a semicolon immediately before else. Common error when converting from pseudo-code

Total = 0;

Use of = instead of := for assigning control variable in for loop e.g.

For loop control variable must be simple local variable

':=' expected but '=' found

for Count = 1 to 5 ...

Use of := instead of = Type of expression in test of equality e.g. must be BOOLEAN

"THEN" expected but ":=" found

if Total := 10 then ...

Variable given same identifier as the program

Identifier redeclared

Duplicate identifier

Identifier of variable contains space e.g.

',' or ':' expected but …

":" expected but …

var my num : real;

Identifier of variable

identifier/declaration "BEGIN" expected but Identifier must begin

Description of error begins with digit e.g.

Typical message content in Delphi

Typical message content in Lazarus

Comment

expected but number "ordinal const" found with letter or found underscore

var 2ndPlace : string;

Identifier of procedure begins with digit e.g.

identifier expected but number found

"identifier" expected but "ordinal const" found

Identifier must begin with letter or underscore

procedure 5Times;

Use of double quotes Illegal character in instead of single input file ($22) quotes to enclose a string literal e.g.

Illegal character ($22)

Surname := "Coe";

String literal not enclosed by quotes e.g.

Undeclared identifier Identifier not found

Forename := Joe;

Use of round brackets Missing operator or to enclose array index semicolon e.g. MyArray(63)

";" expected but "(" found

Use square brackets to enclose array index.

Real number starts with decimal point e.g.

Illegal expression

Include the leading 0 e.g.

Expression expected but '.' found

MyReal := 0.34; MyReal := .34;

Required unit not included in uses section e.g. power function used without including Math unit

Undeclared identifier Identifier not found

Argument type does Incompatible types not match parameter type when calling a subroutine

Incompatible types

Expression operated on by logical operators not enclosed in brackets.

Incompatible types

Operator not applicable to this operand type

Should be: until (Count = MAX) or Found;

Description of error

Typical message content in Delphi

Typical message content in Lazarus

Comment

e.g. until Count = MAX or Found;

Common run-time errors Some errors cannot be detected by the compiler and only become apparent at run time. For example, errors which depend on the input from a user cannot be predicted by the compiler. Description

Example

Comment

Missing type check, allowing wrong type of data to be entered

Letter "a" entered and assigned to integer variable

Index of array not within declared array bounds

Example of INCORRECT code: If the user hits a wrong key (e.g. 5 instead of 4) there program ArrayBounds; could be a run-time error. {$APPTYPE CONSOLE}{$R+} uses SysUtils; const Sales : array[1..4] of integer = (2435, 3423, 3410, 2865); var Index : integer; begin write('View sales for which quarter? ' + '1, 2, 3 or 4 '); readln(Index); writeln(Sales[Index]); readln; end.

Validate entered data.

The compiler directive {$R+} enables run-time checking of ranges. With the default directive {$R-}, the effects of the user's mistake are difficult to predict. Include validation code to accept only the digits 1 to 4.

Overflow e.g. when a number Example of INCORRECT code: The compiler directive {$Q+} is too large to be held in the enables run-time checking of program Overflow; type of variable used overflow. With the default {$APPTYPE CONSOLE}{$Q+} {$Q-}, the program runs and uses outputs a negative number of SysUtils; milliseconds in January! An var MillisecsPerDay, Jan_ms : integer; integer is held in two's {Use int64 instead of integer to complement format, which make represents a negative this program work.} number when the most begin significant bit is 1. MillisecsPerDay := 24 * 60 * 60 * 1000;

Description

Example

Comment

Jan_ms := MillisecsPerDay * 31; writeln(Jan_ms); readln; end.

Division by 0

Example of INCORRECT code: An entry of 0 for Time will cause a run-time error when program DivisionByZero; Speed is calculated. The {$APPTYPE CONSOLE} program needs validation to uses ensure that Time is greater SysUtils; than zero. (It also needs type var Distance, Time, Speed : real; checking, perhaps using the begin val procedure, to accept only write('Distance in m? '); valid numbers for Distance readln(Distance); and Time). write('Time in s? '); readln(Time); Speed := Distance / Time; write('Speed in m/s: '); writeln(Speed : 6 : 2); readln; end.

Infinite loop

Example of INCORRECT code: The integer Num "misses" the end of the loop, which Num := 0; continues to run. Use safe repeat conditions such as Num := Num + 3; until Num = 10;

until Num >= 10

in this example.

Common logic errors When you have removed all the syntax errors, compile-time errors and run-time errors you may think it is time to heave a huge sigh of relief - but don't forget that there may still be logical errors lurking in your program. Out-by-one (or off-by-one) errors are very common, hence the emphasis on boundary testing in computing courses. The cause of the error is often the operator used, as in the first example below. Description Out-by-one

Example

Comment

Example of INCORRECT code: The >= operator should have been used instead of >. if Marks[i] > PassMark then inc(NumberOfPasses);

Description Out-by-one

Example

Comment

Example of INCORRECT code: The calculated number of coaches may be one less than NumCoaches := NumPeople DIV required. SeatingCapacity;

Example of INCORRECT code: Missing begin and end to group statements intended to be run together depending if Names[i] = SearchName then writeln('Found at position ', i); on some condition Found := True;

This code will assign True to Found whether or not the condition is true. This error is often made when adding an instruction to existing code. If you always use begin and end after then, else and do, your programs will be safeguarded from this type of error.

Semicolon immediately after then, else or do

Example of INCORRECT code: In this code the for loop has no code to execute other for i := 1 to 10 do; than incrementing i. After the writeln('Line ', i); loop, the writeln statement is executed once using the final value of i.

Operator precedence not what is required to give the right answer

Example of INCORRECT code: The operators * and / have precedence over + and -. In Celsius := Fahrenheit - 32 * 5 / 9 order to perform the subtraction first, the expression Fahrenheit - 32 should be enclosed in brackets. Tip: If you are unsure of the operator precedence, use brackets to force the order of calculation to be the one you require.

Avoiding mistakes Follow these tips to reduce the number of errors in your programs:    

Take frequent breaks; mistakes are more likely when you are tired. If in doubt, check. Look at examples if you are unsure of the correct syntax. Read the checklists above from time to time and be on the lookout for those mistakes. Learn from your mistakes. Try to recognise the types of mistake you make most often and concentrate on reducing those. Do not rely on the compiler to find your mistakes; it will only find certain types of mistake.



 

Check the computer output carefully to make sure it is correct. Your tests should include normal, boundary and erroneous data. See our sample test plan in the tutorial on testing. Include checks in the program itself, such as validating the input and intermediate results. Try your hand at spotting the errors in our selection of Programs to Debug. See how many of our deliberate errors you are

Getting Started with Form-based Applications in Lazarus Introduction The following topics will help you to use Lazarus to write simple form-based applications using buttons, edit boxes, labels and labelled edits. You will learn about the essential code and files that comprise an application and how to create an application from existing unit and form files. You can then follow our tutorial on form-based applications to learn how to use further components such as the string grid, DBGrid, DBEdit, DBMemo, timer, dialogue boxes and the form's canvas. In the instructions we will give the key combinations for actions where possible. This table shows ways of firing commonly used actions in the order they appear in the Lazarus menu structure. Menu

Action

Button (showing tooltip)

Short-cut Key(s)

File > Open ...

Open file

Ctrl+O

File > Save All

Save all files

Shift+Ctrl+S

View > Object Inspector

Show Object Inspector

F11

View > Units ...

Open View project units dialogue

Ctrl+F12

View > Forms...

Open View project forms dialogue

Shift+F12

View > Toggle form/unit Swap view of form/unit view

F12

Menu

Action

Button (showing tooltip)

Short-cut Key(s)

Project > New Project ... Open Create a new project dialogue Project > Add editor file to Project

Add file showing in editor to project

Shift+F11

Run > Run

Run program

F9

For the screenshots in the following topics we have dragged the dialogue boxes to convenient sizes, so do not expect yours to look exactly the same. Click on the first topic title below, to continue: 1. Writing your First Form-based Application using Lazarus How to write your first form-based "Hello World" application using Lazarus 2. Simple data input How to input data to a form-based application using Lazarus 3. Using two forms How to use more than one form in Lazarus applications 4. Creating a form-based application using existing files How to create a Lazarus application using existing .lfm, .pas and .lpr files 5. Using a Lazarus Project Information (.lpi) File How to use a .lpi file to save and load project information

Writing your First Form-based Application using Lazarus Before doing this exercise you must first have Lazarus installed on your PC. The steps to output "Hello World!" on a form are as follows:

1. Start Lazarus by double-clicking on its Launch icon button.

, or by using the Start

After Lazarus has started, you will see the following menu bar:

2. On the menu bar click on Project. 'Project' is circled in purple in the graphic above. A drop-down menu will appear:

3. On the drop-down menu, click on New Project .... The Create a new project dialogue appears:

4. Select Application if not already selected then click on the OK button. You may see the following Project changed dialogue:

5. If do see the above Project changed dialogue, just click on the No button if you have made no unsaved changes to your previous project. If you do not see the above dialogue you do not need to do anything in this step. 6. Save all files. Shift+Ctrl+S gives the Save project dialogue followed by the save unit dialogue. Navigate to a suitable folder and save the project as HelloWorld to which Lazarus will give the .lpi extension. Save the unit as uHelloWorld, to which Lazarus will be give the .pas extension. (You will be given the option to change to all lower case but you can keep the mixed case name). 7. Open the View forms dialogue (Shift+F12) then select Form1 and click on the OK button. 8. Click on the Abc button then on the form to add a label component to the form.

The label icon is shown here with its tooltip. (Make sure that the Standard tab of components is selected). 9. View the Object Inspector (F11) and type Hello World! as the caption of the label.

10. Press the F9 key to run the program. The files will be saved automatically, so you do not need to save them first. After a small delay, you should see a form appear.

(Our executable at 12.4 MB is rather large for this tiny functionality!) 11. Click on the cross at the top right of the form to make the program terminate. Alternatively, as with console programs, you can click on the Lazarus stop icon (a red square to the right of the start icon). 12. Open the View project units dialogue (Ctrl+F12) then select uHelloWorld.pas The essential code is: unit uHelloWorld; interface uses Classes, SysUtils, FileUtil, Forms, Controls, Graphics, Dialogs, StdCtrls; type TForm1 = class(TForm) Label1: TLabel; end; var Form1: TForm1; implementation {$R *.lfm} end.

13. Press Ctrl+F12 again and view HelloWorld.lpr. The essential code in HelloWorld.lpr is simply: program HelloWorld; uses Interfaces, Forms, uHelloWorld; begin Application.Initialize; Application.CreateForm(TForm1, Form1); Application.Run; end.

14. View Form1 again, right click on it and select View Source (.lfm)

The text view of our form is: object Form1: TForm1 Left = 670 Height = 240 Top = 255 Width = 320 Caption = 'Form1' ClientHeight = 240 ClientWidth = 320 LCLVersion = '0.9.30' object Label1: TLabel Left = 38 Height = 21 Top = 29 Width = 86 Caption = 'Hello World!' ParentColor = False end end

15. If you can think of anything we could have made more straightforward for you, then please let us know. If it did not work, then please tell us what went wrong. Features introduced:    

New form-based application opened Project and unit named Label component used Text output to screen using label

If you want to, you can quit from Lazarus by selecting menu item File > Quit Alternatively, you can move on to the next topic in this guide. The next program, GreetUser has a little more functionality.

Simple data input You can use a simple edit box (tool-tip TEdit) to enter data, but you would need to add a label to inform the user what to put in it. A labelled edit positions conveniently a label next to the edit box. The steps to output the text in a labelled edit box to a separate label on a form are as follows: 1. Create a new application and save the project as GreetUser.lpi and the unit as uGreetUser.pas. 2. Open the form and add a label (tool-tip TLabel ) and button (tool-tip TButton) from the Standard tab of components and a labelled edit (tool-tip TLabeledEdit) from the Additional tab.

3. Rename the components by changing in the Object Inspector the Name properties of the form, label, button and labelled edit to frmGreeting, lblGreeting, btnGreeting and leForename, respectively. 4. Using the Object Inspector, change the Caption property of the form, label, and button to Greeting, blank (by deleting the contents), and Greet me, respectively. 5. Using the Object Inspector for the labelled edit, click on the + to the left of EditLabel then change the caption of the EditLabel to Enter forename then press button. 6. Double click on the button in the form to create the procedure TfrmGreeting.btnGreetingClick(Sender: Tobject) then enter between begin and end the three lines: 7. 8. 9.

lblGreeting.Font.Color := clRed; lblGreeting.Caption := 'Hello ' + leForename.text + '!'; leForename.text := '';

10. Position the components to your satisfaction. 11. Run the program to obtain:

Features introduced:    

Labelled edit box for data input Using string data from an edit box Button component used Meaningful names given to components

Using two forms To access one form from another you need to include the unit of the accessed form in the uses section of the other form. The next topic will have a demonstration of four forms linked together. The steps to link a main form to a password form are given below. We keep it

simple, and do not encrypt the password (or make it difficult to guess). If you go wrong you can look at the essential code of five files after the instructions. 1. Create a new application and save the project as Password.lpi and the unit as uPassword.pas. 2. Open the form and add a button (tool-tip TButton) from the Standard tab of components and two labelled edits (tool-tip TLabeledEdit) from the Additional tab. 3. Rename the components by changing in the Object Inspector the Name properties of the form, button and labelled edits to frmPassword, btnMain, leName and lePassword respectively. 4. Using the Object Inspector, change the Caption property of the form and button to Password Form and Main Form, respectively. 5. Using the Object Inspector for the first labelled edit, click on the + to the left of EditLabel then change the caption of the EditLabel to Name. 6. Using the Object Inspector for the second labelled edit, change the PasswordChar property from #0 to *. Click on the + to the left of EditLabel then change the caption of the EditLabel to Password. 7. Add a new form to the project using the menu item File > New Form. 8. Using the menu item File > Save As ..., save the unit of the new form as uMain.pas. 9. Using the Object Inspector, change the name of the form to frmMain and its caption to Main Form. 10. Add a label to form frmMain and change its name to lblMain 11. At the beginning of the implementation section of the unit uMain.pas, add the code 12. uses 13. uPassword;

14. At the beginning of the implementation section of the unit uPassword.pas, add the code 15. uses 16. uMain;

17. View frmPassword and double click on the button. In its click event procedure insert the code: 18. if lePassword.Text = 'pp4s' then 19. frmMain.Show;

20. View frmMain and open the Object Inspector. Select the Events tab for the form, select the OnActivate event and double click in its empty edit box to be taken to the FormActivate procedure in the editor. Insert the code 21. lblMain.Caption:= frmPassword.leName.Text + ', this is the main form.';

22. Run the program and enter 'Mo' for the name and 'pp4s' for the password.

23. Click the button to see

The essential code for the files follows. Project file Password.lpr program Password; uses Interfaces, Forms, uPassword, uMain; {$R *.res} begin Application.Initialize; Application.CreateForm(TfrmPassword, frmPassword); Application.CreateForm(TfrmMain, frmMain); Application.Run; end.

uPassword.pas unit uPassword; interface uses Classes, SysUtils, FileUtil, Forms, Controls, Graphics, Dialogs, ExtCtrls, StdCtrls; type TfrmPassword = class(TForm)

btnMain: TButton; leName: TLabeledEdit; lePassword: TLabeledEdit; procedure btnMainClick(Sender: TObject); end; var frmPassword: TfrmPassword; implementation uses uMain; {$R *.lfm} procedure TfrmPassword.btnMainClick(Sender: TObject); begin if lePassword.Text = 'pp4s' then frmMain.Show; end; end.

uPassword.lfm object frmPassword: TfrmPassword Left = 504 Height = 119 Top = 303 Width = 397 Caption = 'frmPassword' ClientHeight = 119 ClientWidth = 397 LCLVersion = '0.9.30' object leName: TLabeledEdit Left = 57 Height = 28 Top = 46 Width = 80 EditLabel.AnchorSideLeft.Control = leName EditLabel.AnchorSideBottom.Control = leName EditLabel.Left = 57 EditLabel.Height = 21 EditLabel.Top = 22 EditLabel.Width = 41 EditLabel.Caption = 'Name' EditLabel.ParentColor = False TabOrder = 0 end object lePassword: TLabeledEdit Left = 176 Height = 28 Top = 46 Width = 80 EchoMode = emPassword EditLabel.AnchorSideLeft.Control = lePassword EditLabel.AnchorSideBottom.Control = lePassword EditLabel.Left = 176

EditLabel.Height = 21 EditLabel.Top = 22 EditLabel.Width = 63 EditLabel.Caption = 'Password' EditLabel.ParentColor = False PasswordChar = '*' TabOrder = 1 end object btnMain: TButton Left = 292 Height = 25 Top = 47 Width = 92 Caption = 'Main Form' OnClick = btnMainClick TabOrder = 2 end end

uMain.pas unit uMain; interface uses Classes, SysUtils, FileUtil, Forms, Controls, Graphics, Dialogs, StdCtrls; type TfrmMain = class(TForm) lblMain: TLabel; procedure FormActivate(Sender: TObject); end; var frmMain: TfrmMain; implementation uses uPassword; {$R *.lfm} procedure TfrmMain.FormActivate(Sender: TObject); begin lblMain.Caption:= frmPassword.leName.Text + ', this is the main form.'; end; end.

uMain.lfm object frmMain: TfrmMain Left = 433 Height = 50 Top = 330 Width = 320

Caption = 'Main Form' ClientHeight = 50 ClientWidth = 320 OnActivate = FormActivate LCLVersion = '0.9.30' object lblMain: TLabel Left = 8 Height = 1 Top = 8 Width = 1 ParentColor = False end end

Features introduced:    

New form added to project Other form opened Data entered into one form accessed from another FormActivate procedure used

Creating a form-based application using existing files For form-based applications in our tutorials and student projects we will make available for download a zip file containing .lfm, .pas and .lpr files. This demonstration in form_menu_demo.zip is an example with several simple units and forms. In some cases the set-up is more complicated and we will supply also the .lpi project information file. See the following page for details. 1. Unzip the files to what will be the program folder. (In this case form_menu_demo will be the default). 2. In Lazarus type Ctrl+O, navigate to the program folder then open the .lpr file (in this case MenuDemo.lpr). 3. Select the default type of new project – Application. You can compile and run the program without further changes, but in order to view units or forms you must add them to the project. Follow these instructions to achieve this conveniently using the Project Inspector. 4. Select the menu item Project > Project Inspector then click on the + button in the Project Inspector to see the Add to project dialogue box. 5. Select the Add Files tab then browse to the program folder. Select all the .pas files and open them. The files now appear in the Add to project dialogue box. 6. Select the same files again:

7. Click the Add files to project button. Still in the Object Inspector, you can now double click on a filename to view the code of that unit then press F12 to toggle between a unit and its form. We show below the contents of MenuDemo.lpr, uMenu.pas, uMenu.lfm, uRed.pas and uRed.lfm. Project file MenuDemo.lpr program MenuDemo; uses Interfaces, Forms, uMenu, uRed, uGreen, uBlue; begin Application.Initialize; Application.CreateForm(TfrmMenu, frmMenu); Application.CreateForm(TfrmRed, frmRed); Application.CreateForm(TfrmGreen, frmGreen); Application.CreateForm(TfrmBlue, frmBlue); Application.Run; end.

uMenu.pas unit uMenu; interface uses Classes, SysUtils, FileUtil, Forms, Controls, Graphics, Dialogs, StdCtrls; type TfrmMenu = class(TForm)

btnRed: TButton; btnGreen: TButton; btnBlue: TButton; procedure btnBlueClick(Sender: TObject); procedure btnGreenClick(Sender: TObject); procedure btnRedClick(Sender: TObject); end; var frmMenu: TfrmMenu; implementation {$R *.lfm} uses uRed, uGreen, uBlue; procedure TfrmMenu.btnRedClick(Sender: TObject); begin frmRed.show; end; procedure TfrmMenu.btnGreenClick(Sender: TObject); begin frmGreen.show end; procedure TfrmMenu.btnBlueClick(Sender: TObject); begin frmBlue.show; end; end.

uMenu.lfm object frmMenu: TfrmMenu Left = 670 Height = 91 Top = 255 Width = 320 Caption = 'Menu Form' ClientHeight = 91 ClientWidth = 320 LCLVersion = '0.9.30' object btnRed: TButton Left = 16 Height = 25 Top = 24 Width = 75 Caption = 'Red Form' OnClick = btnRedClick TabOrder = 0 end object btnGreen: TButton Left = 120 Height = 25

Top = 24 Width = 80 Caption = 'Green Form' OnClick = btnGreenClick TabOrder = 1 end object btnBlue: TButton Left = 224 Height = 25 Top = 24 Width = 75 Caption = 'Blue Form' OnClick = btnBlueClick TabOrder = 2 end end

uRed.pas unit uRed; interface uses Classes, SysUtils, FileUtil, Forms, Controls, Graphics, Dialogs, StdCtrls; type TfrmRed = class(TForm) btnMenu: TButton; procedure btnMenuClick(Sender: TObject); end; var frmRed: TfrmRed; implementation {$R *.lfm} uses uMenu; procedure TfrmRed.btnMenuClick(Sender: TObject); begin hide; frmMenu.show; end; end.

uRed.lfm object frmRed: TfrmRed Left = 795 Height = 240 Top = 270 Width = 320

Caption = 'Red Form' ClientHeight = 240 ClientWidth = 320 Color = clRed LCLVersion = '0.9.30' object btnMenu: TButton Left = 16 Height = 25 Top = 16 Width = 75 Caption = 'Menu' OnClick = btnMenuClick TabOrder = 0 end end

(The files uGreen.pas and uBlue.pas are very similar to uRed.pas and the forms uGreen.lfm and uBlue.lfm are very similar to uRed.lfm). Features introduced:    

Existing files unzipped to program folder New application created using .lpr file Units and forms added to project Default name of executable changed

Using a Lazarus Project Information (.lpi) File When you save a project, Lazarus stores all details of the project in the .lpi file by default. You can open it with a text editor to see the values stored. This file has XML format and stores information such as:     

the name of the project; the required packages (often just LCL, which is automatically included in a forms application); the units and associated forms; the details of these files when you viewed them last; the "jump history" (lines you have navigated to by CTRL-clicking in the source code).

In the previous page we showed you how to add files to a project. If you have the .lpi file of a project in your program folder, the necessary files are already part of the project from the outset. For example, using the same example as on the previous page, within the ProjectOptions tag of our MenuDemo.lpi project information file is the following units tag.

{Units 3 - 8 omitted}

We chose the project option to save our session information in the .lps file. Compare this entry in the .lps file for Unit 1 with the above:

By saving our session info in the .lps file, we have prevented this data from being saved in the .lpi file. Similarly our jump history appears in the .lps file rather than the .lpi file. For some programs we will provide the .lpi file for your use. This is particularly helpful when we have added packages to the project. An alternative method for obtaining a suitable .lpi file for distribution is to publish the project. Publishing strips out the details that are unhelpful to an end user. Carry out the following steps to save session information in the .lps file. 1. Select the menu item Project > Project Options 2. Select the Session page 3. Select the option to save session information in the .lps file in the project directory To publish the project, select the menu item Project > Publish Project ... then select or navigate to a suitable Destination Directory. If you want a compressed file of your project, select the appropriate "Command after" from the combo box. Click on the Ok button to publish. Features introduced:

   

New application created using .lpi file Examining an .lpi file Saving session information in the .lps file Publishing a project

Links Online Books and Tutorials Learn Pascal by Tao Yue This clearly written Pascal tutorial includes programming assignments and solutions. Pascal Programming Tutorials by Sheepdog Software Do not be put off by the "no frills" appearance of this site. The tutorials begin with straightforward examples, giving plenty of detail. They cover interesting extras such as playing sounds, and progress to advanced material. Some examples use the crt unit, which is present in Lazarus but not in Delphi. The crt unit includes the ClrScr procedure to clear the screen and the GoToXY procedure to position the cursor before writing to the screen. There are useful links to resources on other websites, often covering difficult topics. How to Program in Pascal and Delphi by Sylvia Langfield Google Books has put online a significant number of pages from the Pascal section of this excellent book. The Pascal Programming Language by Bill Catambay These pages have links to Pascal resources for a variety of operating systems, with many references to the Mac OS.

Online Help/Reference DelphiBasics This impressive site is most helpful for visual programming in Delphi because it gives form-based rather than console-based examples. It is packed with useful information about the Pascal language, however, and can be a useful source of help for console programs as you become more experienced. Ignore the “Show full unit code” option for viewing examples and use the writeln procedure instead of ShowMessage. Reference Guide for Free Pascal (Free Pascal is used by Lazarus.) These authoritative pages include plenty of examples and cover the basics through to advanced features of the languages. Differences from Delphi and Turbo Pascal are noted.

Pascal Dialects The Oxygene Language Smart Pascal DWScript

Pascal as a Stepping Stone CodeShow Monitor this new site for student programs in languages other than Pascal and for brief "Getting Started" guides to other languages and technologies. A working knowledge of Pascal/Object-Pascal will be assumed. CodeShow also has links to material on this site.

Online Dictionaries FOLDOC The Free Online Dictionary of Computing includes “anything you might expect to find in a computer dictionary”. Webopedia Webopedia claims to be “the only online dictionary and search engine you need for computer and Internet technology definitions.”

Challenges Olympiad The British Informatics Olympiad, sponsored by Lionhead Studios, is a programming competition. In the first round, taken at their own school, students attempt to solve three challenging problems in three hours. The top fifteen competitors in the nation are invited to the final. The website has further details, past papers for download and some of the solutions. All Ireland Competition: Sample problems and solutions Some of the problems are straightforward, but you are advised to solve them completely within the time limit. Project Euler "Project Euler exists to encourage, challenge, and develop the skills and enjoyment of anyone with an interest in the fascinating world of mathematics." You are able to access a discussion thread for a particular problem once you have solved it. You may find algorithms that are more efficient than your own and it is interesting also to compare your code with solutions written in other languages.

Game Development Pascal Game Development Webmaster AthenaOfDelphi ensures that the site is a good source of news (such as advances in Lazarus and Delphi), tutorials and discussions. She is organising the development of the PGD Community Engine, which should allow students to produce even better games. Pascal Gamer Magazine The magazine, edited by Jason McMillen, is a free, downloadable publication covering game development and design with Pascal and Object Pascal development

tools. A section of the site provides a showcase for past PGDAnnual competitions and, most usefully, source code for entries for Dogfight (the 2005 competition). Freepascal meets SDL An excellent site for learning how to use the Simple DirectMedia Layer NeHe Productions 3D demonstrations and tutorials

Examination Board Computing Resources (Specifications, past papers, mark schemes and examiner reports) AQA GCE A-level Computing AQA GCSE Computer Science Specification CIE (University of Cambridge International Examinations) A & AS Level Computing Edexcel GCSE Computer Science OCR AS/A Level GCE Computing OCR GCSE Computing WJEC Computing GCE A/AS

View more...

Comments

Copyright ©2017 KUPDF Inc.
SUPPORT KUPDF