About Delphi Programming - For Novice Developers and First Time Visitors
About Delphi Programming - For Novice Developers and First Time Visitors
By Zarko Gajic
Delphi Expert
Updated February 16, 2016.
Hi! I'm Zarko Gajic, your About.com Guide to Delphi Programming. That's my picture at the top
of the page (or maybe at the bottom). You can read my bio to learn more about who I am. I
write feature articles and tutorials related to Delphi programming. I also gather links to other
sites that have articles, tutorials, and important information on specific aspects of programming
in the Delphi language.
The purpose of this page is to orient newcomers with an overview of some special features of
the About Delphi Programming Web site.
Before you start exploring the vast amount of Delphi related topics this site covers, I would
strongly suggest signing up for the FREE Delphi Newsletter (no spam 100%) - to make sure you
are up-to-date with new Delphi tutorials, articles and tips posted daily on About Delphi
Programming.
Embarcadero Technologies Delphi is an object-oriented, visual programming environment to
develop 32 and 64 bit applications; with FireMonkey, Delphi is the fastest way to deliver ultrarich and visually stunning native applications for Windows, Mac and iOS.
If you are just entering the programming world, here's why you should consider learning
Delphi: Why Delphi?. Also, don't miss Delphi History!
If you are confused about different Delphi versions (Delphi Starter, Delphi XE2, RAD Studio),
read the "Flavors of Delphi" article to easily pick your Delphi of choice.
There is a lot of information on this site about Delphi programming; this site covers all aspects
of Delphi development, including tutorials and articles, forum, language reference with
examples, glossary, free code programs, custom components and much more.
Let me help you find what you're looking for (and help your career by looking for the right
Delphi job). Learn how Delphi can help you solve complex development problems to deliver
high-performance, highly scalable applications ranging from Windows and database
applications to mobile and distributed applications for the Internet.
If you simply want to build a simple database application (accounting, CD/DVD album), for
home use, Delphi will help you build it fast and with ease.
Looking for something specific?
You can search this Delphi Programming site or all of About.com for a specific programming
task. Try it using the search box at the top of the page. Hint: Put phrases in double-quotation
marks for better results (i.e. "protected hack"). If you are looking for more ways to find Delphi
programming related materials, go see the "Searching for Delphi" article.
True Beginners, Students, Newcomers ...
For those who are new to Delphi, I've prepared several free online courses designed to get you
to a fast start. The free courses below are perfect for Delphi beginners as well as for those who
want a broad overview of the art of programming with Delphi.
Be sure not to miss the Delphi Tutorials and Online / Email Courses section.
How to program in Delphi what you need to know?
This entire site is devoted to providing the tutorials and other resources needed to learn Delphi
programming. There are several broad categories of Delphi programming tutorials to help you
in your quest to learn how to create the best solutions fast. These include tutorials for the
beginner as well as the more experienced developer, find them listed in A Beginner's Guide to
Delphi [enter Delphi topic].
If you are looking for free or/and shareware and commercial components, youll be happy to
know Ive prepared a dozen of Top Picks pages where all the best third-party components,
tools and Delphi books are collected and reviewed.
Be the first to know!
Related
1. How to Layout Delphi Project Files (Best Practice) for Source Control System
Ok this is now for real. Do not even start a single form application if you do not have some kind
of source control set up.
Also, do not put all files in a single folder - make sure you follow some Delphi project
organisation best practices.
After a month or two, year or two, you might want to go back to your first application and
change something - but you do not have the source code :(
Source / Revision Control, in short, helps you have a place to store your source code, provides a
historical record of what you have done over time, can provide a way for developers to work on
separate tasks.
Where to Find Glyphs and Icons for a Delphi Application, Menu, Toolbar
Glyph and Icon collections
Delphi IDE Tools and Plug-Ins Every Developer Should Use
5. Reporting System
As your application grows you'll start to look for a reporting system. Some included some from
third-party - reporting tools let you easily create complex reports that are linked directly into
your Delphi EXE. Most of the tools provide all the means for you to develop reports, including a
report engine, report designer, previewer, ...
6. Help Authoring
Documentation and the help system is essential when users are working with your applications.
Help your users with multiple language support, WYSIWYG interfaces, and more. You can create
manuals in PDF, HTML, HTML Help, Windows Help and RTF.
Developers will get up to speed quickly through real world, practical examples.
This course is aimed to those who are new to programming, come from some other
development environment (like MS Visual Basic, or Java) or are new to Delphi.
Prerequisites:
Readers should have at least a working knowledge of the Windows operating system.
Chapters
The chapters of this course are being created and updated dynamically on this site. You can find
the latest chapter on the last page of this article.
Start with Chapter 1 : Introducing Borland Delphi
Then continue learning, this course already has more than 18 chapters ...
The chapters of this course are being created and updated dynamically on this site. Chapters
(for now) include:
CHAPTER 1:
Introducing Borland Delphi
What is Borland Delphi? Where to download a free version, how to install and configure it.
Discuss about questions, comments, problems and solutions related to this chapter!
CHAPTER 2:
A journey through the Delphi IDE
A quick journey through the main parts and tools of the Delphi integrated development
environment.
Discuss about questions, comments, problems and solutions related to this chapter!
CHAPTER 3:
Creating your first *Hello World* Delphi Application
An overview of application development with Delphi, including creating a simple project,
writing code, compiling and running a project. Also, find out how to ask Delphi for help.
Discuss about questions, comments, problems and solutions related to this chapter!
CHAPTER 4:
Learn about: properties, events and Delphi Pascal
Create your second simple Delphi application allowing you to learn how to place components
on a form, set their properties, write event handler procedures to make components
cooperate together.
Discuss about questions, comments, problems and solutions related to this chapter!
CHAPTER 5:
Understanding the Delphi unit source
Take a closer look at exactly what each keyword means by examining each line of the Delphi
form unit source code. Interface, implementation, uses and other keywords explained in easy
language!
Discuss about questions, comments, problems and solutions related to this chapter!
CHAPTER 6:
An introduction to Delphi Pascal
Before you start developing more sophisticated applications by using the RAD features of
Delphi, you should learn the basics of the Delphi Pascal language.
Discuss about questions, comments, problems and solutions related to this chapter!
CHAPTER 7:
Sophisticated Delphi Pascal techniques for Beginners
Time to extend your Delphi Pascal knowledge to the max. Here are some intermediate Delphi
Like most other development tools (and unlike other Windows applications), Delphi IDE
comprises a number of separate windows.
The main window, positioned on the top of the screen, contains the main menu, toolbar and
Component palette. The title bar of the main window contains the name of the current project
(you'll see in some of the future chapters what exactly is a Delphi project). The menu bar
includes a dozen drop-down menus - we'll explain many of the options in these menus later
through this course. The toolbar provides a number of shortcuts to most frequently used
operations and commands - such as running a project, or adding a new form to a project. To
find out what particular button does, point your mouse "over" the button and wait for the
tooltip. As you can see from the tooltip (for example, point to [Toggle Form/Unit]), many
toolbuttons have keyboard shortcuts ([F12]).
The menus and toolbars are freely customizable. I suggest you to leave the default arrangement
while working through the chapters of this course.
The Component Palette
You are probably familiar with the fact that any window in a standard Windows application
contains a number of different (visible or not to the end user) objects, like: buttons, text boxes,
radio buttons, check boxes etc. In Delphi programming terminology such objects are called
controls (or components). Components are the building blocks of every Delphi application. To
place a component on a window you drag it from the component palette. Each component has
specific attributes that enable you to control your application at design and run time.
Depending on the version of Delphi (assumed Delphi 6 Personal through this course), you start
with more than 85 components at your disposal - you can even add more components later
(those that you create or from a third party component vendor).
The components on the Component Palette are grouped according to the function they
perform. Each page tab in the Component palette displays a group of icons representing the
components you can use to design your application interface. For example, the Standard and
Additional pages include controls such as an edit box, a button or a scroll box.
To see all components on a particular page (for example on the Win32 page) you simply click
the tab name on the top of the palette. If a component palette lists more components that can
be displayed on a page an arrow will appear on a far right side of the page allowing you to click
it to scroll right. If a component palette has more tabs (pages) that can be displayed, more tabs
can be displayed by clicking on the arrow buttons on the right-hand side.
Next page > The Delphi IDE; Main menu, toolbar > Page 1, 2
Form1 window
Each time you start Delphi, a new project is created that consists of one *empty* window. A
typical Delphi application, in most cases, will contain more than one window - those windows
are referred to as forms. In our case this form has a name, it is called Form1. This form can be
renamed, resized and moved, it has a caption and the three standard minimize, maximize and
close buttons. As you can see a Delphi form is a regular Windows window.
Unit1.pas - the Code Editor window
If the Form1 is the active window and you press [F12], the Code Editor window will be placed
on top. As you design user interface of your application, Delphi automatically generates the
underlying Object Pascal code. More lines will be added to this window as you add your own
code that drives your application. This window displays code for the current form (Form1); the
text is stored in a (so-called) unit - Unit1. You can open multiple files in the Code Editor. Each
file opens on a new page of the Code editor, and each page is represented by a tab at the top of
the window.
Related Resources
Before you create your first Delphi project, you A Beginner's Guide to
need to know what you want to develop; a DLL, Delphi
Programming.TOC
MDI application, SDI application a CLX
application (for Linux) or something else. To start
without all the bells and whistles we'll create a standard SDI Windows
application. Simply point your mouse to File | New and select Application.
This creates a new project group with a single application in it.
The new project contains an empty form, a unit (associated with its form), and a project file. As
you develop and build your application, new files will be created and added to the project. The
project files are listed in the Project Manager window, display it by selecting View | Project
Manager from the main Delphi menu. With the Project Manager, you can easily visualize how
all your project files are related. If you share files among different projects, using the Project
Manager is recommended because you can quickly and easily see the location of each file in the
project.
end
For the moment do not get bothered with the meaning of the text you see.
Now alter the code so that it looks like:
procedure TForm1.FormCreate(Sender: TObject);
begin
Caption := 'Hello Delphi! ' + DateTimeToStr(Now);
end
Running a project for the first time
To see the results of this action, you need to (successfully) compile and run you project. From
the Run menu choose Run or press F9. The compiler will try to build the project and execute
your application. If the compiler encounters an error, it displays an Error dialog box. When you
choose OK to dismiss the dialog box, the Code editor places the cursor on the line of code
containing the error.
Note: if you want to see progress reports while your program compiles, you'll need to check the
"Show compiler progress" check box in the "Compiling and running" section on the Preferences
page of the Environment Options dialog box. Call this dialog box by selecting Environment
Options from the Tools menu.
If everything goes well (it should) your application is executed and you see a blank form on the
screen. Note several things. First, the form is blank - there are no dots that make up the grid
you see when designing the form look. Second, there is a new button on the Windows Task Bar
- when you point to it you'll see that it has the Project1 caption. Third, the caption of Delphi IDE
is changed from "Delphi 6 - Project 1" to "Delphi 6 - Project 1 [Running]". And fourth, most
important for us, the caption of the form is Hello Delphi ! + *date and time of the execution*.
There is not much you can do with this window, you can move it resize it and finally close it.
Every time you (compile and) run this project a form caption will say Hello Delphi with the date
and time of the execution.
Ok, I know this is not a lot, but be patient - this is your first project - it is not supposed to do
something meaningful. If you want a little more, here goes another simpe example.
Page 3: Saving your work. Getting help from Delphi.
Saving the project
To properly get the job done, you should save the project, along with
all its associated files. To save the current form design and its code,
select File | Save All from the main menu bar. By default, Delphi
opens the Projects folder. I suggest you to create a new folder
(inside the Projects folder) for your project. Let's call it
"HelloExample". While in the Save As dialog, open the newly created
HelloExample folder and save the following files:
. save Unit1 as MainUnit.pas
. save Project1 as HelloProject.dpr
Note 1: When you have saved the unit file, the corresponding form
was saved as MainUnit.dfm
Note 2: In the Code Editor window, Unit1 is now referred to as
MainUnit.
Note 3: Since you have saved the project with the *new* name, if
Related Resources
you run your application now, the button on the Task Bar will say
"HelloProject". Of course the name of the application and the name A Beginner's Guide to
of the project do not need to be the same, later we will see how to Delphi
Programming.TOC
change the name of a Delphi application.
Note, if you open up the HelloExample folder in the Windows Explorer, you should find several
files inside it. These are MainUnit.pas, MainUnit.dfm and several others. The most important
file inside this folder is the HelloProject.exe. This is your applications executable file, if you
double click it you'll execute it. If you want to "install" your application on another machine this
is the only file you need to copy.
Getting HELP from Delphi
Let's stop for the moment to explore ways to get help from Delphi in situations when help is
necessary. First of all, Delphi is supplied with extensive documentation. If you do not have the
printed manuals, those that came (as PDF) with the installation will do. As stated in the first
chapter of this course, the books include:
. Quick Start - a brief introduction to Delphi,
. Object Pascal Language Guide - a complete reference to the underlying Delphi programming
language, and
. Developers Guide - which covers advanced topics, from creating database applications to
creating your custom components.
Beside printed materials, Delphi holds a great deal of information in the Help system. Even
though you'll need to learn how to use it, it is really worth it - there are many code examples to
help you understand all the nuts and bolts of Object Pascal programming. What's more,
context-sensitive Help is available from nearly every portion of the Code editor. To get contextsensitive Help from the Code editor window simply place the cursor on the property, event,
method, procedure or type for which you want Help, then press F1.
Try it. Position the mouse cursor inside the word "Caption" in the Code Editor (the word
Caption you typed in the only example so far) and hit the F1 key.
Once you press the F1 key, a pop up window will ask you to specify more exactly what you want
to know. Here comes the hard part: how in the world you know what topic to pick. The
"problem" lies in the fact that, in Delphi, many components have properties of the same name
(and behavior). To get the help on Form Caption property you need to pick TControl.Caption.
Why TControl, when you are working with Form not something called TControl? Well, for the
moment this is hard to explain, let's just say that Form derives from something called Control
and that Control has a Caption property. What you will find out is that in general, Caption is
used for text that appears as a window title.
But how will you know what to pick? There is a solution. Point to Object Inspector, Properties
page. Select the property you want to find out about and than press F1.
Some exercises for you...
Since this Course is an online course, there is much you can do to prepare for the next chapter.
At the end of each chapter I'll try to provide several tasks for you to get more familiar with
Delphi and the topics we discuss in the current chapter. Here are some exercises for you:
0. Learn about the Name property of the Form object. Note that the Name property should tell
you what the form does.
1. Explore the Object Inspector and try to figure what properties relate to the Form positioning
on the screen (Left, Top, Width, Height, ...) and what happens when you alter them at design
time.
2. Try to change the color of the Form from the Object Inspector (Color property)
3. Learn about the BorderIcons and BorderStyle properties and how they relate to visual
representation of the Form at run time.
4. Find what exactly DateTimeToStr is used for.
5. Be sure not to miss the next chapter!
To the next chapter: A Beginner's Guide to Delphi Programming
This is the end of the third chapter, in the fourth chapter, you'll create a second simple
application allowing you to learn hot to place components on a form, set their properties, write
evnet handler procedures to make components work together.
If you need any kind of help at this point, please post to the Delphi Programming Forum where
all the questions are answered and beginners are treated as experts.
Learn about: properties, events and Delphi Pascal
Page 1: Placing Components on a Form
Welcome to the fourth chapter of the FREE online programming
course:
A Beginners Guide to Delphi Programming.
Create your second simple Delphi application allowing you to learn
hot to place components on a form, set their properties, write event
handler procedures to make components cooperate together.
Note: even though at this stage of the Course, it is not important to create "nicely looking" user
interfaces, I strongly encourage you to always try to arrange components on form so they
create a user friendly interface. Here are some suggestions and Standards of Screen Design.
Next page > Changing Component Properties; Writing Code - Events and Event Handlers >
Page 2: Changing Component Properties; Writing Code - Events and Event Handlers
Changing Component Properties
After you place components on a form, you can set their properties
with the Object Inspector. The properties are different for each type
of component, some properties apply to most components. Altering
a component property, changes the way a component behaves and
appears in an application.
All the components have a property called "Name". The Name
property is very important; it specifies the name of the component
as referenced in code. When you first place a component on a form,
Delphi will provide a default name for the component: Label1, Edit1,
Button1. I suggest you to give your components a meaningful name
before writing the code that refers to them. You can do this by
changing the value of the Name property in the Object Inspector.
Here are some suggestions on how to give names to components.
Related Resources
A Beginner's Guide to
Note: with the last statement in mind, I'll do the opposite. In most
cases, I'll leave all the default component names through this Course Delphi
Programming.TOC
- just as they appear when you place them on a form.
To actually change a component property you first need to activate it - click it to select it - small
square handles appear at each corner and in the middle of each side. Another way to select a
component is to click its name in the drop down list that appears at the top of the Object
Inspector. This list lists all the components on the active form along with their types in the
following format: "Name Type".
When a component is selected, its properties (and events) are displayed in the Object
Inspector. To change the component property click on a property name in the Object Inspector;
then either type a new value or select from the drop-down list.
For example, change the Caption property for Button1 (I'll refer components by their names) to
Components have different kinds of properties; some can store a boolean value (True or False),
like Enabled. To change a boolean property double click the property value to toggle between
the states. Some properties can hold a number (e.g. Width or Left), a string (e.g. Caption or
Text) or even a set of "simple valued" properties. When a property has an associated editor, to
set complex values, an ellipsis button appears near the property name. For example if you click
the ellipsis of the Font property a Font property dialog box will appear.
Now, change the Caption (the static text the label displays on the form) of Label1 to 'Your name
please:'. Change the Text property (text displayed in the edit box - this text will be changeable
at run time) of Edit1 to 'Zarko Gajic' (this is my name, write your name).
Writing Code - Events and Event Handlers
To really enable components to do something meaningful you have to write some actionspecific code for each component you want to react on user input. Remember: components are
building block of any Delphi form, the code behind each component ensures a component will
react on an action.
Each Delphi component, beside its properties, has a set of events. Windows as even-led
environment requires the programmer to decide how a program will (if it will) react on user
actions. You need to understand that Windows is a message-based operating system. System
messages are handled by a message handler that translates the message to Delphi event
handlers. For instance, when a user clicks a button on a form, Windows sends a message to the
application and the application reacts to this new event. If the
OnClick event for a button is specified it gets executed.
The code to respond to events is contained in Delphi event
procedures (event handlers). All components have a set of
events that they can react on. For example, all clickable
components have an OnClick event that gets fired if a user clicks
a component with a mouse. All such components have an event
for getting and loosing the focus, too. However if you do not
specify the code for OnEnter and OnExit (OnEnter - got focus; OnExit - lost focus) the event will
be ignored by your application.
To see a list of events a component can react on, select a component and in the Object
Inspector activate the Events tab. To really create an event handling procedure, decide on what
event you want your component to react, and double click the event name.
For example, select the Button1 component, and double click the OnClick event name. Delphi
will bring the Code Editor to the top of the screen and the skeleton code for the OnClick event
will be created.
procedure TForm1.Button1Click(Sender: TObject);
begin
//this is where your code goes
end
Note: For the moment there is no need to understand what all the words in the above code
stand for. Just follow along, we'll explain all that in the following chapters.
As you will understand more clearly through this course, a procedure must have a unique name
within the form. The above procedure, Delphi component event-driven procedure, is named for
you. The name consists of: the name of the form (prefixed with T) "TForm", a full stop ".", the
component name "Button1", and the event name "Click". For any component there is a set of
events that you could create event handlers for. Just creating an event handler does not
guarantee your application will do something on the event - you must write some event
handling code in the body of the procedure.
A few words on Delphi (Object) Pascal
The code you write inside event procedures is Pascal code. Object Pascal or Delphi Pascal (as I
will mostly call it), a set of object-oriented extensions to standard Pascal, is the language of
Delphi. Delphi Pascal enables you to take advantage of object-oriented programming to its
fullest. It can be said that Delphi Pascal is to Pascal what C++ is to C. As Delphi was being
developed, new language behavior and keywords were added to deal with the component
model. In general, Delphi Pascal is a high-level, compiled, strongly typed language that supports
structured and object-oriented design.
We'll now write some code for the OnClick event handler of Button1. Alter the above
procedure body to:
procedure TForm1.Button1Click(Sender: TObject);
var s: string;
begin
s := 'Hello ' + Edit1.Text + ' Delphi welcomes you!';
ShowMessage(s);
end;
A few words on Delphi Code completion
When you reach to the second line and write "Edit1."
wait a little, Delphi will display a list box with all the
properties of the edit box you can pick. In general, it
lists valid elements that you can select from and add
to your code. Here's more info on Delphi Code Insight
tools.
Now, hit F9 to compile and run your project. When the program starts, click the Button1
('Hello...'). A message box will pop up saying 'Hello Zarko Gajic, Delphi welcomes you!'. Change
the text in the Edit box and hit the Button again...
What follows is a simple explanation of the code that runs this application. Let's see.
The first line under the procedure name, var s: string;, declares a string type variable.
Variables in Delphi Pascal hold information (values). Variables have to be declared before they
can be used. We do this after the var keyword.
The first line under the begin keyword, s := 'Hello ' + Edit1.Text + ' Delphi welcomes you!'; sets
a value for the variable s. This assignment involves reading a value of the Text property for the
Edit component. If you ask Delphi about the Text property of an Edit component, you'll find out
that it holds the text string that is displayed in the edit box. That text is of the TCaption type,
actually the string type.
The last statement, before the end keyword, ShowMessage(s);, is the one that calls the
message dialog and sends it the value of variable s - this results in a pop up box your see above.
That's it. Again, not too smart, not too hard but serves the purpose. By now you should know
how to place components on a form, set their properties and even do a small do-somethingfunny Delphi application. Be sure to visit all the links in the above paragraph.
Some exercises for you...
Since this Course is an online course, there is much you can do to prepare for the next chapter.
At the end of each chapter I'll try to provide several tasks for you to get more familiar with
Delphi and the topics we discuss in the current chapter. Here are some exercises for you, after
you finish reading this chapter:
1. Play with the Color property of the Form object
2. Use the Font property Editor to alter the font of the TLabel component
3. Find out about the PasswordChar property of the TEdit component to create a simple
password dialog form
4. Try adding a code for the OnCreate event of a form to make a form appear centered on a
screen. Also, make yourself familiar with the Position property of the TForm object.
5. Be sure not to miss the next chapter!
To the next chapter: A Beginner's Guide to Delphi Programming
This is the end of the fourth chapter, in the fifth chapter, we'll explore the Code Editor window
to help you in understanding the source behind the Form widow.
If you need any kind of help at this point, please post to the Delphi Programming Forum where
all the questions are answered and beginners are treated as experts.
Understanding the Delphi unit source
Page 1: Delphi Unit source code
Welcome to the fifth chapter of the FREE online programming
course:
A Beginner's Guide to Delphi Programming.
Take a closer look at exactly what each keyword means by examining
each line of the Delphi form unit source code. Interface,
implementation, uses and other keywords explained in easy
language!
Note another thing: in the above code, black lines appear in the forms unit source the first time
you add a form to a project. Lines colored in green were added by Delphi when you have placed
those three components on a form. Lines in red were added by you in the previous chapter.
Whenever you create a new form, Delphi creates the corresponding unit file with the skeleton
code marked black.
The rest of the article will discuss parts of the unit source. Several new words like class, object
and similar will be mentioned, do not get frightened if you do not understand what they mean,
let's just say that such words are a part of Delphi object oriented programming, we will discuss
them in the following chapters more clearly.
Page 2: Interface, implementation, uses and other keywords explained in easy language!
The UNIT keyword
A unit file begins with a unit heading, which is followed by the
interface, implementation, initialization, and finalization sections.
The initialization and finalization sections are optional.
The unit heading starts with a word unit (line 01), followed by a unit
(file) name. The unit name (Unit1 in the above source) must match
the unit file name on a disk. In a single project all unit names must
be unique. You should change the unit's name only by using the FileSave As command from the Delphi IDE main menu. Of course, it is
completely up to you to decide how will you name your units. In
most cases you'll want your units to have the name similar to the
name of the form to which they are linked, like 'MainUnit' for Main
form (form with a Name property set to 'Main'). Be sure to give
name to units in the early stage of a form design development.
Related Resources
A Beginner's Guide to
Delphi
Programming.TOC
The INTERFACE section
The interface section of a unit starts with the word interface (line 02) Project Unit
and continues until the word implementation (line 17). This section Unit Sections
is used to declare any public sections of code that appear in a unit. TForm:
The entire contents of the interface section, including type, variable Birth/Life/Death
and procedure declarations, are visible to any other unit which uses
this unit. When any other part of the program looks at a unit, all it sees is the interface section.
Everything else is hidden, internal to the unit, part of the implementation. You could say that
the interface section contains a list of items in the unit that other units can use.
In most cases the interface section will define several "subsections", you can see that the code
for unit1.pas has a uses clause, a type section, and a variable declaration section.
The INTERFACE USES section
If the interface section includes a uses clause, it must appear immediately after the word
interface. A uses clause (line 03) lists units used by the unit. In most cases, all necessary units
are placed in the interface uses clause when Delphi compiler generates and maintains a units
source. The Windows, Messages, SysUtils, etc are all standard Delphi units, required by a
program.
As you drop components on a form, the necessary units will be added automatically to the uses
clause. For example, if you add a TOpenDialog component on your form (Dialogs page on the
component palette), the Dialogs unit will appear in the uses clause because it contains the logic
for the TOpenDialog component (and other Dialog components).
In some situations, you'll need to manually add units to interface uses clause. Suppose you are
to use the TRegistry object, designed to access the Windows Registry. You cannot drop the
TRegistry component on a form, since it does not appear on the component palette - you must
manually add the word Registry to the uses list.
The INTERFACE TYPE section
Another part of the interface section is the type section. The form type declaration (or form
class declaration) section introduces the form as a class. The code from line 04 to 14 declares
the existence and structure of a class called TForm1.
A few words on classes and objects
I'm aware that this is not the place to explain OOP in Delphi, but I sense that something must be
stated. The basics of object oriented programming in Delphi will be discussed in the next
chapter of this course, however some words must be explained now.
A class, or class type, defines a structure consisting of fields, methods, and properties. Instances
of a class type are called objects.
For example, in real world, a class PROGRAMMER can have properties like:
Years_Of_Experience and Projects_Developed. It can expose methods like: Write_Program and
Talk_To_Users. A class is something that does not truly exists. An object: DELPHI
PROGRAMMER is a specific instance of a class.
Anything that appears in a unit's implementation section that is not referenced in the interface
is private to that unit. This means that a procedure or function declared and defined
(implemented) in the implementation section cannot be called from another unit unless its
header is listed in that unit's interface.
The INITIALIZATION and FINALIZATION sections
These two sections are optional; they are not automatically generated when we create a unit. If
we want to initialize any data the unit uses, we can add an initialization code to the initialization
section of the unit. When an application uses a unit, the code within the unit's initialization part
is called before the any other application code runs.
If your unit needs to perform any cleanup when the application terminates, such as freeing any
resources allocated in the initialization part; you can add a finalization section to your unit. The
finalization section comes after the initialization section, but before the final end.
Other units of a Delphi project
Now, when you have learned about the structure of a Delphi form unit, it's time to see what
other units can appear in a project. Every Delphi program has at least two main parts. The first
is a project file such as Project1.dpr. You can see the structure of the project file by pointing
you mouse to Project|View Source from the Delphi main menu. The second part is one (or
more) units attached to forms - the structure of such a unit is discussed through this article.
However, units don't have to be associated with forms. A Code Unit contains code that is called
from other units in the project. When you start building libraries of useful routines, you will
probably store them in a code unit. To add a new code unit to Delphi application choose FileNew ... Unit. The structure of a code unit is similar to form unit, it only lacks the type
declaration for the "linked" TForm class.
Looking in the past: Code Explorer
In the second chapter of this course you have learned the main
parts of the Delphi IDE. When we were discussing the Code Editor
window, one part of that window was left unexplained - the Code
Explorer. By default, the Code Explorer is docked to the left of the
Code editor.
The Code Explorer makes it easy to navigate through your unit
source. The Code Explorer contains a tree diagram that shows all
the types, classes, properties, methods, global variables, and global
routines defined in your unit. It also shows the other units listed in
the uses clause.
I use the Code explorer to quickly jump to a procedure or type declaration by simply doubleclicking on an item name, like Button1Click.
To the next chapter: A Beginner's Guide to Delphi Programming
This is the end of the fourth chapter, in the next chapter, you'll learn about the Delphi Pascal the language of Delphi.
If you need any kind of help at this point, please post to the Delphi Programming Forum where
all the questions are answered and beginners are treated as experts.
Delphi For Beginners:
Object Pascal Variable Scope
As mentioned in some of the previous articles understanding Object Pascal variable scope is
one of key elements in building applications with Delphi/Object Pascal.
have been initialized" warning. This means that, before using declared variable, it is a good
practice to initialize it (just to be sure). For that purpose add this line of code before
ShowMessage...
SomeNumber := 123.45;
7. Now, when you run your project message box will display 123,45 (no errors, no warnings).
Finally, we can see why local variables are called local...
8.Add one TButton component to form and double-click it to create Buttons OnClick event
handler. Add the following code (so that OnClick looks like):
procedure TForm1.Button1Click(Sender: TObject);
begin
ShowMessage(FloatToStr(SomeNumber));
end;
Again we have "Undeclared Identifier: 'SomeNumber'" error. This is what local variables are all
about: even if we have declared (and initialized) SomeNumber variable in OnCreate event
handler of the form, SomeNumber is not accessible in the OnClick handler of TButtton. We
simply cannot use SomeNumber (with 123.45 value) in the OnClick (at least for now). This
means that SomeNumber from OnCreate and SomeNumber from OnClick are two different
variables (that can, of course, hold different values)
9. Don't close this project, jet. We will need it again...
10. Add the following line before ShowMessage in the OnClick event handler (we will need it
later, don't worry about this for now)
SomeNumber:=555.55;
Sharing variables across procedures (event handlers)
Occasionally we will want to share the values of variables (and constants) across event handlers
or across units. For example, if an application is designed to perform a calculation involving one
SomeNumber at a time, that SomeNumber should be available to all procedures in a unit.
Depending on where we declare a variable, the variable can be thought of as a true global
variable accessible by any other code in the application, or a unit-level variable accessible by
any code in the unit.
Unit level variables - unit level scope
We put the declaration statements for unit-level variables in a var section in the unit's
implementation section. Unit-level constants are declared in a const section.
const
clicks : Integer = 1; //not a true constant
begin
Form1.Caption := IntToStr(clicks) ;
clicks := clicks + 1;
end;
Notice that every time you click on the button, forms caption increments steadily.
Now try the following code:
procedure TForm1.Button1Click(Sender: TObject) ;
var
clicks : Integer;
begin
Form1.Caption := IntToStr(clicks) ;
clicks := clicks + 1;
end;
We are now using uninitialized variable for the clicks counter. Notice that weird value in the
forms caption after you click on the button.
Constant typed constants
You have to agree that idea of modifiable constants sound a bit strange. In 32 bit versions of
Delphi Borland decided to discourage their use, but support them for Delphi 1 legacy code.
We can enable or disable Assignable typed constants on the Compiler page of the Project
Options dialog box.
If you've disabled Assignable typed constants for a given project, when you attempt to compile
previous code Delphi will give you 'Left side cannot be assigned to' error upon compilation. You
can, however, create assignable typed constant by declaring:
{$J+}
const clicks : Integer = 1;
{$J-}
Therefore, the first example code looks like:
procedure TForm1.Button1Click(Sender: TObject) ;
const
{$J+}
clicks : Integer = 1; //not a true constant
{$J-}
begin
Form1.Caption := IntToStr(clicks) ;
clicks := clicks + 1;
end;
Conclusion
It's up to you to decide whether you want typed constants to be assignable or not. Important
thing here is that besides ideal for counters, typed constants are ideal for making components
alternately visible or invisible, or we can use them for switching between any Boolean
properties. Typed constants can also be used inside TTimer's event handler to keep track of
how many times even has been triggered.
If you want some more beginners material check the rest of the Delphi For Beginners
programming topics.
The loop is a common element in all programming languages. Delphi has three control
structures that execute blocks of code repeatedly: for, repeat ... until and while ... do.
The FOR loop
Suppose we need to repeat an operation a fixed number of times.
// show 1,2,3,4,5 message boxes
var j: integer;
begin
for j := 1 to 5 do
begin
ShowMessage('Box: '+IntToStr(j)) ;
end;
end;
The value of a control variable (j), which is really just a counter, determines how many times a
for statement runs. The keyword for sets up a counter. In the preceding example, the starting
value for the counter is set to 1. The ending value is set to 5.
When the for statement begins running the counter variable is set to the starting value. Delphi
than checks whether the value for the counter is less than the ending value. If the value is
greater, nothing is done (program execution jumps to the line of code immediately following
the for loop code block). If the starting value is less than the ending value, the body of the loop
is executed (here: the message box is displayed).
continue reading below our video
How Does 3D Printing Work?
Play
0:00
/
1:09
Fullscreen
Finally, Delphi adds 1 to the counter and starts the process again.
Sometimes it is necessary to count backward. The downto keyword specifies that the value of a
counter should be decremented by one each time the loop executes (it is not possible to specify
an increment / decrement other than one). An example of a for loop that counts backward.
var j: integer;
begin
for j := 5 downto 1 do
begin
ShowMessage('T minus ' + IntToStr(j) + 'seconds') ;
end;
ShowMessage('For sequence executed!') ;
end;
Note: it's important that you never change the value of the control variable in the middle of the
loop. Doing so will cause errors.
Nested FOR loops
Writing a for loop within another for loop (nesting loops) is very useful when you want to fill /
display data in a table or a grid.
var k,j: integer;
begin
//this double loop is executed 4x4=16 times
for k:= 1 to 4 do
for j:= 4 downto 1 do
ShowMessage('Box: '+ IntToStr(k)+ ',' + IntToStr(j)) ;
end;
The rule for nesting for-next loops is simple: the inner loop (j counter) must be completed
before the next statement for the outer loop is encountered (k counter). We can have triply or
quadruply nested loops, or even more.
Note: Generally, the begin and end keywords are not strictly required, as you can see. If begin
and end are not used, the statement immediately following the for statement is considered the
body of the loop.
The FOR-IN loop
If you have Delphi 2005 or any newer version, you can use the "new" for-element-in-collection
style iteration over containers. The following example demonstrates iteration over string
expressions: for each char in string check if the character is either 'a' or 'e' or 'i'.
const
s = 'About Delphi Programming';
var
c : char;
begin
for c in s do
begin
if c in ['a','e','i'] then
begin
// do something
end;
end;
end;
The WHILE and REPEAT loops
Sometimes we won't know exactly how many times a loop should cycle. What if we want to
repeat an operation until we reach a specific goal?
The most important difference between the while-do loop and the repeat-until loop is that the
code of the repeat statement is always executed at least once.
The general pattern when we write a repeat (and while) type of loop in Delphi is as follows:
repeat
begin
statements;
end;
until condition = true
while condition = true do
begin
statements;
end;
Here is the code to show 5 successive message boxes using repeat-until:
var
j: integer;
begin
j:=0;
repeat
if iNumber = 0 then
begin
ShowMessage('Zero value encountered!') ;
Exit; // exit from the current procedure
end;
//if iNumber is 0 the folowing
//code will never be executed
ShowMessage('Nobody likes 0, ha!') ;
end;
More often, we will want to process multiple statements if a condition is True or False.
var iNumber : Integer;
begin
//some value must be
//assigned to iNumber here!
if iNumber < 0 then
begin
//statements ...
ShowMessage('Your number is negative!') ;
//statements ...
end
else
begin
//statements ...
ShowMessage('Your number is positive or zero!') ;
//statements ...
end;
end;
Note: Each statement in the begin..end block ends with a semicolon. We cannot have a
semicolon before or after the else keyword. The if-then-else statement, is a single statement,
therefore we cannot place a semicolon in the middle of it.
An if statement can be quite complex. The condition can be turned into a series of conditions
(using the and, or and not Boolean operators), or the if statement can nest a second if
statement.
var
iNumber : Integer;
begin
if iNumber = 0 then
begin
ShowMessage('Zero number not allowed!') ;
exit;
end
else
Note 2: If you want to include more than one statement in the part following the colon (:), place
the begin and end keywords around the multiple statements.