Delphi Tutorial – Lesson 2 More Delphi Stuff 1/4/99 Frank Fortino [email protected] Copyright 1999

Delphi Tutorial – Lesson 2 More Delphi Stuff 1/4/99
Frank Fortino [email protected] Copyright 1999

File I’m attaching:

HelpLib1.zip – the first chunk of my Help text file snippets – Unzip this inside its own directory.
Email0199.ZIP – Sample code

These Help snippets come from:
-Delphi newsgroups
-Sample programs from book CDs
-Delphi’s Help (F1)
-Code from my test (example) programs

If you need WinZip you can get it from the www.winzip.com site or email me and I will send you a copy.
Main Topics:

-Object or Component?
-Property, Method, Event?
-Structure of Unit1.dfm file and Form1
-Delphi and Windows95 (a little multitasking info)
-Setting Project Options, Environment Options.
-Third Party Components from the WEB
-Installing New Components and Packages
-Make It Work, Make It Easy to Debug
-Global Variables
-Using BreakPoints to better understand Delphi

Hi again,

I sent you the HelpLib1.zip file to start your Help Library. The more code examples that you read, the more you will see similarities and the common structure of Delphi Pascal.

When I first started reading Delphi code, I only knew what a few lines meant; everything else didn’t make sense. (e.g. (Sender : TObject) )

When You really learn Delphi, you will understand EVERY LINE of code.

For Beginners who havethe book ‘Mastering Delphi 2,3 or 4’; here are the Chapters (from MD3) that I recommend that you read first.

Chapter
——————————–
1 Form is a Window
2 Delphi Environment
4 Pascal Lang.
8 Tour of Basic Comps
13 Multiple Forms $ Dialog Boxes
16 Building DB Apps
…then the other chapters

OK Let’s get started on More Delphi Stuff.

What is an OBJECT (Component)?

Remember a Component is an Object on your Palette
-an Object, can be a Component on your Palette,
-or something that is created totally in code

-So an OBJECT is a more general class of things, than a COMPONENT
-All Components are Objects
-But Not All Objects are Components (TStringList is an Object, and Not a Component)

I sometimes slip and call Components Objects (and so do some other people).
-What is a PROPERTY?

-A Property is nothing more than a Variable (e.g. word, string,…) that has some built-in Methods (functions) to Read and Write to it’s Variable.

COMMENT:
I sometimes use these words to mean the same thing (but they are different):
-Procedure (a chunk of code that does something)
-Function (a procedure that Returns a Value (e.g. Result:=1; )
-Method (a proc. or function built into a Component)
-Subroutine (a generic term, I think from BASIC)
-What is a METHOD?

-A Method is a function that is attached to an Object
For Example:
a ListBox (which can hold an array of strings) has a Method (Clear) that makes all the strings =” in the ListBox.

CLEAR is a Method of the ListBox.

begin
ListBox1.Clear; // Clears the ListBox
end;

Also, Properties of a Component can have their own Methods
(e.g. Items, is a Property of ListBox)
Items, is of type TStrings
TStrings, has a Method ‘LoadFromFile’ that Opens, Reads and Closes a File

ListBox1.Items.LoadFromFile(‘c:Data1.txt’);

-What is an EVENT?

-An Event is a User Action (Mouse Click, KeyPressed,…)
Events all begin with the word ‘On’

——————————–
OnClick .. Button1Click(Sender : TObject)
OnKeyDown .. Button1KeyDown(Sender : TObject)
OnMouseMove .. Button1MouseMove(Sender : TObject)

Events are where you write your Delphi code.
Using this TUTORIAL

1) There is no overall order to the TOPICS
2) Each TOPIC should stand on its own You don’t have to read 2 pages ahead.
Simple Experiment to better understand Delphi (.dfm/Form):

-New Form (Form1)
-Add Button (Button1)
-Click on Form1
-Alt F12 (switches to Unit1.dfm – same as View As Text)

Note: You can use Alt F12 to Toggle back and forth from (Form1 to Unit1.dfm)

What do you see?

Unit1.dfm File (as a text file – which it is not)

object Form1: TForm1 // Here’s the Form1 defined
Left = 200
Top = 108
Width = 696
Height = 480
Caption = ‘Form1’
Font.Charset = DEFAULT_CHARSET
Font.Color = clWindowText
Font.Height = -11
Font.Name = ‘MS Sans Serif’
Font.Style = []
PixelsPerInch = 96
TextHeight = 13
object Button1: TButton // Oh Here’s Button1 defined (under Form1)
Left = 220 // Form1 is the Parent(and Owner) of Button1
Top = 120
Width = 75
Height = 25
Caption = ‘Button1’
TabOrder = 0
end
end

OK Now

-Click on the Unit1.dfm text
-Alt F12 (to see Form1 again – same as View As Form)

-Add a Panel (Panel1)
-In Object Inspector change Panel1’s Color to RED

-Click on Form1
-Alt F12 (View As Text)

What do you see?

object Form1: TForm1
Left = 200
Top = 108
Width = 696
Height = 480
Caption = ‘Form1’
Font.Charset = DEFAULT_CHARSET
Font.Color = clWindowText
Font.Height = -11
Font.Name = ‘MS Sans Serif’
Font.Style = []
PixelsPerInch = 96
TextHeight = 13
object Button1: TButton
Left = 220
Top = 120
Width = 75
Height = 25
Caption = ‘Button1’
TabOrder = 0
end
object Panel1: TPanel // Here’s Panel 1 defined
Left = 284
Top = 204
Width = 185
Height = 41
Caption = ‘Panel1’
Color = clRed // YES the Color is RED
TabOrder = 1
end
end

Do you see what Delphi is doing.

As you add Components to Form1 and change Properties, Delphi is creating (pseudo) code (in Unit1.dfm) to define what you did.

Normally YOU DO NOT CHANGE the Unit1.dfm File; You should only work on the Visual Form1.

And now for something completely different.

How does Delphi and your Delphi program work with Windows 95

(The following is not very technical, it is only trying to explain in simple terms, how things work)

What is Delphi?

-The Delphi (IDE) is a Visual Interface between You (the User) and your Computer (that is running Windows 95).

-Delphi translates the Visual Components (Buttons, Panels,..) on your Form (your Form is basically a Window to Win95); into an interim (pseudo) language (in Unit1.dfm) that defines how to build the Form and Components; and also defines all the Properties of the Components.

When you Compile your program; What happens?
-Delphi goes to the .dpr file (your project file)
-Delphi asks – What Program Chunks are in the Project
-.dpr file answers:

uses
Forms,
Unit1 in ‘Unit1.pas’ {Form1}; // Oh Unit1 and Form1

-Delphi asks – What do I do first
-.dpr file answers:
————-

begin
Application.Initialize; // Initializes stuff
Application.CreateForm(TForm1, Form1); // Creates Form1
// using the Unit1.dfm file
Application.Run; // Runs Program
end.

————-

Now you are inside your Program, waiting for Events (User Actions) to be sent to you from Win95.

The MASTER (Win95) is running on your Computer, and every time the User Clicks the Mouse or Hits a Key; Win95 (by way of the Applications Interface (Win API)) sends your Program a Message.

– Remember Application.ProcessMessages (from Lesson 1)

What ‘Application.ProcessMessages’ does, is it gives Control back to Win95, so that Win95 can Process Keys etc. and Display windows (your Form is a window)

Remember your Computer is only 1 Little Guy (Pentium…) trying to do multiple things at one time (MultiTasking).

What Tasks does Win95 do? (only some of the things it does):
-Watches the Keyboard
-Watches the Mouse
-Draws Windows on your Monitor (Screen)
-Runs your Program
-Runs other programs

Win95 does MultiTasking by controlling your Computer; and only Running each Task for a short period of time (say 50 msec) then switching to the next Task for (50 msec) then switching to the next Task … finally getting back to the first Task.

So Win95 makes your Computer look like a Multiple number of programs are All Running at the same time.

BUT MULTIPLE PROGRAMS ARE NOT RUNNING AT THE SAME TIME!

It is just multiple Tasks being Run in a loop (by 1 guy).

That’s why you must use ‘Application.ProcessMessages’ inside your Button Click Event. (as described in Lesson 1)

You have to relinquish Control back to Win95, in the middle of the Button Click procedure; so that Win95 can look for Key Hits and Draw your Form.
Setting up your PROJECT and ENVIRONMENT OPTIONS

(following is the way that I have my Delphi 3 Pro IDE setup)

-Project(menu)
-Options
-Compiler(tab)

Code gen. Runtime …
X Aligned record… ALL CHECKED

Syntax … Debugging …
X Stack – ALL CHECKED
X Extended –
X Open –
X Huge – Messages
X Assembler- ALL CHECKED

———————-

-Tools(menu)
-Environment Options
-Preferences

X Desktop Only X Editor files
X Desktop

Form Designer sizeX 4
ALL CHECKED sizeY 4

Debugging Compiling …
X Integrated- X Show-
X Break – X Minimize-
X Hide-
————————————————–

-Library
X Show Hints
X Show Messages
————————————————–

-Code Insight
X Code Completion
X Code Params
X Tool tip Expression Eval.

————————————————–

-Colors

Select Colors for:
Comment (Red)
Reserved word (Blue)
String (Pink)
Delphi Inconsistencies:

1) .dpr and .pas Cannot have the same name. Why not?
One file is FSysSet.dpr and the other is FSysSet.pas // Not Allowed

That’s why I always put a ‘P’ at the end of the Project file:
FSysSetP.dpr

2) You CANNOT change the Color of a Button

Most Components allow you to change their Color, But Not a Button
Why Not?
Because (for some reason) Delphi does not draw the Button, it has Windows 95, draw the Button; so Windows uses the Default Button Color (in your Windows Setup).

3) Delphi (Depending where you are in Delphi) uses:
-FLOAT, REAL, SINGLE, DOUBLE and NUMBER All for float type variables
-CURRENCY and MONEY for currency type

4) Delphi’s Help examples are shared for different topics,
Probably to save space. It would help us learn more, if they had individual, simple examples.

For example: If you look up ‘FORMAT FUNCTION’ you get one tiny example; while Format has 8 different format types.
They should, show us an example that uses all 8 types.
Third Party Components

This is another resource you have to improve your Delphi POWER TOOLS. I’ve downloaded hundreds of really neat stuff.

But if I look at my installed Components; I don’t see many that I use; that I didn’t have to pay for.

This does not mean that you should not Download free Components.

You should Download anything that catches your eye.

Examples of where Free Components that can improve Delphi:
-Colored Buttons
-Improved DBGrids (that auto-link to LookupComboBoxes)
-Database stuff
-RS232 Serial Component
-…

The best sites that I have found, and use all the time:

DELPHI SUPER PAGE
http://sunsite.icm.edu.pl/delphi/

TORRY”S DELPHI PAGES
http://www.torry.ru/index.htm is.

Both have Components sorted by Category.

There will also be a wide range of usefull components available from this site in the near future. Later I will try and accumulate a list of good add-on Components.

Installing New Components

This is more complicated than it should be.

First you Should Create a New Package – All Components go into Packages

You DON’T want to Install New Components in the Packages that Borland gives use (at least not normally).

You do not want to corrupt the installed Delphi Packages.

To Create a New Package you have to Install a New Component into it.
(we should be able to just create a Package, before we add Components, but we can’t)

Creating a New Package (and Installing a Component)
-Component(Menu)
-Install Component
-Into New Package(Tab)
-Enter Name PACKAGE FILE NAME e.g. ‘Test1’
-Browser(Button)
-Pick .pas or .dcu File (for the New Component)
(that you Downloaded from the Web)
-Open
-OK
-hit OK …
-Exit (X on top right of Dialog Box (Dialog Form)

Note: You can Install a Component from a .pas or a .dcu
If you only have a .dcu (built by Delphi3), D4 will not Install it. If you have the .pas then, D4 can install it.
Installing a New Component in an Existing Package:
-Component(menu)
-Install Component
-Select PACKAGE NAME FILE (e.g. ‘Test1’)
-Browse (for UNIT FILE NAME) (as .pas or .dcu)
-Pick a file
-Open
-OK
-Confirm YES
————–

Later I will show you how to Uninstall a Component.
It is a little weird. I have to investigate it further.
Another Topic:

I looked at some other free Delphi Tutorials; GEEZE! They either don’t say much, and don’t cover much territory; or they are too detailed, and go so slow.

When I was trying to learn Delphi, I got little or no help from them.

Anyway, I am going to cover a lot of turf, trying to give you some good advice (and also some of my (sometimes not mainstream) design Principles).

Hopefully when I am all done, I will have given you:
-A list of DO’s and DON’Ts
-A programming Philosophy (Style and Principles)
-A Library of Important stuff
-An Overview of how Delphi works
-Some good Power Tools for you to learn on your own
-Some good examples
-And places to go to get Help

I want to show you how to make your own examples and learn new things.

Like TEACHING YOU TO FISH rather than GIVING YOU FISH. (gosh, is he quoting from the Bible???)

Remember use your books, use the Index and Table of Contents to find all the nitty-gritty details of topics that I expose you to.

These Lessons should not read like a book, all organized with lots of details. You have books for that.

What I want to give you, is another way of seeing Delphi, sometimes looking from above; and sometimes in the inner bowels of Delphi.
QUIZ

1) When you start a New Project what is the first thing you should do?

Tick, Tick, … BEEP Times Up

YES, you should Rename the Form, Unit and Project and save them in their own unique Folder.

2) When you put a Button on the Form, what should you do first?

YES, Rename the Button (e.g. ReadBtn)

3) What is SENDER?

Answer – It’s a parameter(a variable passed to a procedure)
(used by a Delphi Event)

-What type is it?

Ans. – It’s a TObject (YES)

Wait, it’s a TObject; EVERYTHING is a TObject; So What?
That doesn’t tell us much.

-Why is it a type TObject?

Ans. – So that it can be any kind of Component (Button, ListBox, Edit , …)

OOOOh, I see, it’s a general type (TObject) that lets it be assigned to ANY type of Component.

YES, YES

—————
This is fun. I like talking to myself.
—————

4) How do you make a Copy of a Form (explain all the ways)?

-Copying Forms

1) Use Win Explorer to copy .pas .dfm Files (YES)
2) Add Form to Repository (see Lesson 1) (YES)
3) Open the ProjectMgr(Toolbar)
-Select ADD
-Pick .pas file
-A copy of the Form is Added to Project (WRONG)

The Unit and Form get added to the Project, but NO COPY is made of the original Unit & Form,
so any changes you make, will change the Original Form.

Nothing is copied Unless you do:
-File(menu)
-Save As (new file name)

Franks Programming Philosophy 101

1) First Make it Work
Then Make it Pretty
-Organize
-Minimize

2) You can write code (build a project) in 15 minutes, then it takes you 2 hours to make it work right (debug it).

So, what is the most important thing to keep in mind when you write a program?

YES – MAKE IT EASY TO DEBUG (Make it Work)

How, do you make it easier to Debug – you say?

Step 1) Write Inline code first, don’t worry about creating subroutines (procedure) calls for redundant code.

Step 2) Name things compactly, but use names that document what you are doing.

Step 3) Test your program
(remember Murphy’s Law: If it can go wrong it will go wrong)

Step 4) Use every way you know, to make your code easily readable; even use Global variables.

I don’t believe it. Did he say use Globals. Oh No.

COMMENT:

Today’s Headline ‘GLOBALS – Heaven or Hell’

The Great Unknown.

Most people do not know how to use Globals CORRECTLY. They are told to totally avoid them.

There are times when it IS appropriate to use Globals-When it makes your code easier to read and maintain.

Most people don’t have the foggiest idea of WHEN and HOW to use them.

With Global Variables you can:
-Have Access ALL variables from ANYWHERE (in all your Forms(Units))
-Call Procedures without passing Parameters(passing data) or with a minimal number of params

Bad things (difficulties) with Globals
-Someone else can change your data in a multi-programmer project
-A Unit does not stand on its own, if it uses Globals defined in another Unit.

Rules for Using Global Variables:
1) Use them sparingly
2) Keep track of them
-Keep Them in One Place
-Assign them in 1 place; MainProgram or common Unit
e.g. (in MainUnit1.pas)
3) Name them with a X starting char, or some other unique way
So that they STAND OUT.

XFileName : string[100];
XCountyStr : string[32];
XDate : TDate;
XCnts : array[0..255] of byte;

Where do you put Global declarations?

Ans: In the interface section:

var
Form1: TForm1;
XFileName : string[64]; // Global
XDate : TDate; // Global implementation

In later Lessons, I’ll have some sample programs that show you how to define and use Globals.

COMMENT:

Everything that I tell you is not always totally correct, but it’s close enough. To get the real scoop; look things up in Delphi’s Help(F1) and Books.

These Lessons are just to expose you to stuff; and sometimes to look at things from a different angle

But remember; in Delphi, sometimes it’s very hard to go backwards, so try to be consistent.

Also, don’t do all your programming on the Computer. I still use a pencil and paper (A Lot).

And, Clean up your code as you go.

Delphi Insights that I have had in my learning experiences (not in any specific order)

* -Using Breakpoints
* -Using Code Insight
* -Databases
* -Finally seeing how OOP works
* -TStringLists
* -Component Templates (just last week)
* -Form1 and Unit1.dfm structure

I will go into some of these in detail in future Lessons.
This format is fun, I always loved teaching. I only taught Elect. Engrg in College for 2 years.

I always hated homework; and teaching had tons of homework; and the pay sucked.

By the way; I cannot answer many of your individual questions (for now). I really have a lot to tell you, in a short time; so I can’t do things on an individual basis, yet.

But, still send me your comments and questions; since I want to learn more too. And make these Lessons better for future readers.

Here’s how you can help me and others. And that’s the whole idea. These Lessons are pretty crude right now, so I could use some help cleaning them up, improving them, adding to them and organizing things better.

So any help would be greatly appreciated.
When you create simple example programs for yourself; (when you want to better understand a new Component etc.)
Save them, and later we might be able to use them (give them to others) as part of this Tutorial.
Looking at how the style of these Lessons has evolved:
-free form
-changing Topic instantly
-when something new comes up (explain it right there)

Books are different; they are Super organized
-They are great: as a reference, and for details
-They are difficult: when you are first learning and are overwhelmed by a lot of new stuff.

So maybe this is a different way of learning.
Our Learning Group as of 1/13/99, is almost 160 people.
Because of the great response to these Lessons, I decided to let the group expand to 200, for now.

Later, I will put everything on a Web site; with more organization and a lot of examples; but still keeping the compact and intense structure.

If you have anything that you think would help others; please send it to me, so that we can all use it. That way we can all learn together (more quickly).

BACK TO DELPHI

Using Breakpoints to see how Delphi works:

A lot of programmers seldom use BreakPoints(B.P.), or they just use them if they have a coding problem. They are missing another great feature of BreakPoints; to see how Delphi works, and see the sequencing of how your code runs.

Breakpoints:

-New Form
-Add Button1
-Dbl Click Button1
-Add the following code (in Button1’s OnClick Event)

procedure TForm1.Button1Click(Sender: TObject);
var x,y : word;
s : string;
begin
s:=’15’;
x:=StrToInt(s);
x:=x+1;
end;

-Compile(Build All)

-You should see little Blue dots on the left of each line(in Unit1.pas) that you can put a Breakpoint on.

-Click on the Blue dot on line:
x:=StrToInt(s);

-The line should now be highlighted in RED
This means that you added a Breakpoint (B.P.) there.

-Click the RED dot (the Blue dot also turned Red)
The Breakpoint should go away The dot is Blue again

-Click on the Blue dot again
This sets the Breakpoint again

-Now Run the Program and Click Button1
-the Program stops on the line with the B.P.
-Also a little Green Arrow appears by the line;
this tells you that the Program is here (and IT HAS NOT RUN THIS LINE YET)

Now there are 3 important Keys to use:
(DON’T HIT THESE KEYS YET)

F8 will Single Step, and only run 1 line of code.

F9 will Run the Program until it hits another B.P.
If there is no other B.P., then the Program just runs normally.

Ctrl F2 will Reset (Stop) your program

-With the program stopped on your B.P.

-Just move the cursor over the Variable ‘s’
What happens?

A hint pops up with s=’15’
What is going on?

Delphi lets you see the Value of all your Vars; by simple putting the cursor over the Variable.

Touch ‘x’ (put the cursor over it)
It should say x=3462 // or some random number

Why does x=3462 and not x=0?

IMPORTANT POINT

Delphi Automatically Initializes every Global Variable before the Program runs.
Integers are 0 x=0
String are null s=”
arrays are ALL nulls or 0’s

So, you NEVER have to Initialize a Global Variable to 0 or NULL

Local variables are NOT initialized. And x is a Local var.

OK

-Now hit F8
-and the Green Arrow moves to the next line

Touch x
-should show x=15 (in a hint window)

Now STOP YOUR PROGRAM
-How do you Stop the Program?
Ans: Hit Ctrl F2
or -Run(Menu)
-Program Reset

Stops your Program, and puts you back in the Delphi Editor

Now, run the Program again (Hit F9)

-Click Button1 again

And play around with F8, F9 and touching Variables.
Until you understand what’s happening.

You should use Breakpoints, to go inside your code a lot.
That’s how you learn how Delphi works.

Later I will cover Breakpoints and Debugging Techniques in detail, but this is good enough for now.

Write more code, and add Breakpoints.

THIS IS ONE OF THOSE INSIGHTFUL TIMES
At least it was for me, when I first discovered how elegantly Delphi handles Breakpoints.
Frank’s Philosophy

It’s a lot easier to write complicated code.
It takes a lot more understanding to simplify the problem down to it’s ESSENCE.

There is genius (and a lot of hard work) in an Elegant, Simple design.
Thank you Delphi.

One thing to avoid; Do Not get to tricky or compact your code too much.
Remember you want your code to be easy to read and understand.

Which is easier to read: (A or B?)

A B
————————- ——————–

xxxxxxxxxxxxx xxxxxxxxxxx
xxxxxxxxx xxxxxx
xxxxxxxxxxxxx xxxxxxxxxxxxxxxx
xxxxxxx
xxxxxxxxxxxxxxx xxxxxxxxxxxx
xxxxxxxxxxx xxxxxxxx
xxxxxxxxxxxxx xxxxxxxxxxxxxxxxxx
xxxxxxxxxxxxxx xxx
xxxxxxxx
xxxxxxxxxxx xxxxx
xxxxxxxx xxxxxxxxxx

I think B is easier to read (it has more structure)

You should use blank lines to put your code into functional blocks.
That’s it for Now.

In Lesson 3, I will be sending you some sample programs.

What’s coming Next?
-Lesson 3 Databases
-Lesson 4 String Stuff, Debugging Techniques, Conversion Routines and stuff
-Example programs, Code Snippets, Delphi Tools, Components

(boy I sure use the word stuff – a lot)
By for now.

Remember, send me your comments; and any help will be greatly appreciated.

Frank

Reproduced with the kind permission of Frank Fortino.

Comments