About Delphi Programming - For Novice Developers and First Time Visitors

You might also like

Download as pdf or txt
Download as pdf or txt
You are on page 1of 42

About Delphi Programming - for Novice Developers and

First Time Visitors


What You Need to Know About Delphi Programming.

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.

Turbo Delphi Tutorial: For Novice and Non-Programmers


A Beginner's Guide to Delphi Programming
A Beginner's Guide to Delphi Database Programming
A Beginner's Guide to ASP.NET Web programming for Delphi developers

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!

Sign up for your Delphi Programming Newslette


Grab the Delphi Programming Headlines RSS Feed
Follow About Delphi Programming on Facebook

Related

How to Get Started with Delphi Programming


A Beginner's Guide to Delphi Programming Chapters 11-20
Installing the Free Delphi: Turbo Delphi Explorer for Win32 development
Learning Delphi Online

Before You Start a New Delphi Project


I do not know when and where, but long time ago I read the following:
"Delphi programming is the mutts nuts. You can start off not knowing anything about
programming, within 1 hour you can write a program and at the end, still know nothing about
programming :-)"
From my experience I can suggest a few steps you should follow and a few tools you should
have to master Delphi programming.
The "steps" will help you get from the "I have an idea" to the full blown Delphi build
application. The tools should be the building blocks of a Delphi project - tools you need before
you start a new Delphi project.
What Delphi? This can also be Done Using Delphi?
First things first. Since you are reading this I guess your already have selected your environment
for creating Windows applications, and that it is, well, Delphi :)
Nice! Welcome aboard. Do you know that Delphi can do Win32 applications as well as .NET
applications? Do you know there are different Delphi versions and that you should know how to
pick your Delphi version?
When you know what Delphi version you should pick, you should make sure you know how to
create applications using Delphi. Free Delphi online courses should help.

Understand Delphi Versions and Pick your Delphi of Choice


Delphi History from Pascal to Rad Studio 2007
Delphi Tutorials / Online Courses

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.

Delphi Project Structure Folder Organization


What Delphi files to store in a source control system
TortoiseSVN - interface to (Sub)Version Control

2. Extra VCL Controls


Depending on your Delphi version, you will have more than 100 ready made components you
can use. Delphi Components are a part of the VCL. You can place VCL components on forms and
manipulate their properties without writing code.
Developers write different programs. One developer will be happy with the out-of-the-box edit
control (TEdit) provided in the VCL while another would need an super-turbo edit control that
knows what a user is about to write even if he/she does not have a keabord :)
Creating custom components can also be interesting, but you can always look for free Delphi
control libraries.

Free Delphi Component Sets


Understanding, Using and Enhancing Delphi VCL Components
How to Debug Delphi VCL Source Code

3. Glyphs, Icons, Graphics. Delphi IDE Plug-Ins and Add-Ons


Ok, it is not that you can not create a Delphi application without a nicely looking user interface
but if you want to stand out and make your application user interface elements look
professional and unique you'll need a few extra icons and glyphs.
Delphi controls and the VCL allow you to easily setup toolbars, menus and other user interface
elements with custom graphics.
Delphi IDE provides all the tools you need to design, develop, test, debug, and deploy
applications, allowing rapid prototyping and a shorter development time. Want more? Here's
how to add more functionality to Delphi IDE and make your job easier.

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

4. Bug and Exception Logging System


Yes, even the applications that you write are prone to bugs. Sooner or later, as the program
grows, a user of your application will call you saying something like: "there's a dialog saying
something about some 'access violation' - the application then crashed, what should we do?"

madExcept - Delphi Crash / Exception Handling with Bug Reporting


EurekaLog - Bug Resolving Solution

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, ...

Top 10 Delphi Reporting Tools


Quick Reports Tutorial
Database Reports with Delphi and ADO

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.

Top Delphi Help-Authoring Tools


Execute a Custom Action on the Form's Help button Click

7. Setup and Install Building Tools


Even though most Delphi applications can ship as a single EXE file - you should invest the time
into creating a professional installation package.

Top Delphi Setup and Install Building Tools

A Beginner's Guide to Delphi Programming

Getting Started with Delphi


Delphi Programming - Inside and Out
Build Database Applications with Delphi
Free Delphi Source Code: Projects, Controls, Components
Understanding, Using and Enhancing Delphi VCL Components
Using Database Components (DB Aware Controls) in Delphi

Advanced Delphi Windows / Shell / API / Graphics / OLE Programming


Build Network / Internet / Intranet / Distributed Delphi Applications
Learn Delphi for .NET
Top Picks - Delphi Tools and Components
Essential Delphi Tools, Utilities and Resources

Updated October 31, 2015.


About the Course:
This free online course is perfect for beginner developers as well as for those who want a broad
overview of the art of programming with Borland Delphi.
Developers will learn how to design, develop and test application using Borland Delphi. The
chapters will cover the fundamental elements of creating Windows applications using Delphi,
including the Integrated Development Environment (IDE) and the Object Pascal language.

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.

Recommended reading: Delphi history from (Turbo) Pascal to Delphi 2005.


Concise descriptions of Delphi versions and its history, along with a brief list of features
and notes. Find out how Delphi evolved from Pascal to a RAD tool that can help you
deliver high-performance, scalable applications ranging from desktop and database
solutions to mobile and distributed applications for the Internet not only for Windows
but also for Linux and the .NET.

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

problems and articles for everyday development tasks.


Discuss about questions, comments, problems and solutions related to this chapter!
CHAPTER 8:
Commenting Delphi code
Learn the art of helping yourself, when it comes to code maintenance. The purpose of adding
comments to Delphi code is to provide more program readability using understandable
description of what your code is doing.
Discuss about questions, comments, problems and solutions related to this chapter!
CHAPTER 9:
Cleaning your Delphi code errors
A discussion on Delphi design, run and compile time errors and how to prevent them. Also,
take a look at some solutions to most common logic errors.
Discuss about questions, comments, problems and solutions related to this chapter!
CHAPTER 10:
Your First Delphi Game: Tic Tac Toe
Designing and developing a real game using Delphi: Tic Tac Toe.
Discuss about questions, comments, problems and solutions related to this chapter!
CHAPTER 11:
Your First MDI Delphi Project
Learn how to create a powerful "multiple document interface" application using Delphi.
Discuss about questions, comments, problems and solutions related to this chapter!
CHAPTER 12:
Win a copy of Mastering Delphi 7
Delphi Programming Tic Tac Toe Contest - develop your own version of the TicTacToe game
and win one copy of the great Mastering Delphi 7 book.
Discuss about questions, comments, problems and solutions related to this chapter!
CHAPTER 13:
Code Completion in Delphi
It's time to learn how to let Delphi help you code faster: start using code templates, code
insight, code completion, shortcut keys, ...
Discuss about questions, comments, problems and solutions related to this chapter!
CHAPTER 14:
Making Forms Work - a Primer
In just about every Delphi application, we use forms to present and retrieve information from
users. Delphi arms us with a rich array of visual tools for creating forms and determining their
properties and behavior. We can set them up at design time using the property editors and

we can write code to re-set them dynamically at runtime.


Discuss about questions, comments, problems and solutions related to this chapter!
CHAPTER 15:
Communicating Between Forms
In "Making Forms Work - a Primer" we looked at simple SDI forms and considered some good
reasons for not letting your program auto-create forms. This chapter builds on that to
demonstrate techniques available when closing modal forms and how one form can retrieve
user input or other data from a secondary form.
Discuss about questions, comments, problems and solutions related to this chapter!
CHAPTER 16:
Creating flat (non-relational) databases with no database components
Delphi Personal edition does not offer database support. In this chapter, you will find out
how to create your own *flat* database and store any kind of data - all without a single data
aware component.
Discuss about questions, comments, problems and solutions related to this chapter!
CHAPTER 17:
Working with units
While developing a (large) Delphi application, as program becomes more complex, its source
code can become very hard to maintain. In this article you will learn about creating your own
code modues - Delphi code files that contain logically associated functions and procedures.
Along the process we'll briefly discuss using Delphi's built-in routines and how to make all the
units of a Delphi application cooperate.
Discuss about questions, comments, problems and solutions related to this chapter!
CHAPTER 18:
Code navigation in Delphi
How to be even more productive with Delphi IDE (precisely, the code editor): start using code
navigation features - quickly jump from a method implementation and a method declaration,
locate a variable declaration using tooltip symbol insight features, and more.
Discuss about questions, comments, problems and solutions related to this chapter!

The Delphi IDE


As explained in the first chapter of this course, one of the ways to start Delphi is to choose
Programs | Borland Delphi 6 | Delphi 6 from the Windows Start menu.
When Delphi starts (it could even take one full minute to start - depending on your hardware
performance) you are presented with the IDE: the user interface where you can design, compile
and debug your Delphi projects.

Like most other development tools (and unlike other Windows applications), Delphi IDE
comprises a number of separate windows.

The menus, toolbars

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.

The Object Inspector


Each component and each form, has a set of properties - such as
color, size, position, caption - that can be modified in the Delphi IDE
or in your code, and a collection of events - such as a mouse click,
keypress, or component activation - for which you can specify some
additional behavior. The Object Inspector displays the properties
and events (note the two tabs) for the selected component and
allows you to change the property value or select the response to
some event.
For example, each form has a Caption (the text that appears on it's
title bar). To change the caption of Form1 first activate the form by
clicking on it. In the Object Inspector find the property Caption (in
the left column), note that it has the 'Form1' value (in the right column). To change the caption
of the form simply type the new text value, like 'My Form' (without the single quotes). When
you press [Enter] the caption of the form will change to My Form.
Note that some properties can be changed more simply, the position of the form on the screen
can be set by entering the value for the Left and Top properties - or the form can be simply
dragged to the desired location.
The Object TreeView
Above the Object Inspector you should see the Object TreeView window. For the moment it's
display is pretty simple. As you add components to the form, you'll see that it displays a
component's parent-child relationships in a tree diagram. One of the great features of the
Object TreeView is the ability to drag and drop components in order to change a component
container without losing connections with other components.
The Object TreeView, Object Inspector and the Form Designer (the Form1 window) work
cooperatively. If you have an object on a form (we have not placed any yet) and click it, its
properties and events are displayed in the Object Inspector and the component becomes
focussed in the Object TreeView.
Closing Delphi
To stop working in the Delphi IDE, you can point to the File | Exit option in the main menu. If
you have made changes to the current project, you'll be asked if you want to save the changes.
Since this is the first time we've done some changes to the project in this course, and we do not
yet know how a project is saved and what are the options, select [No].
To the next chapter: A Beginner's Guide to Delphi Programming
This is the end of the second chapter, in the third chapter, we'll explore the ways of getting help
from Delphi: about the Object Pascal, user interface, VCL, ...
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.

Creating your first 'Hello World' Delphi Application


Page 1: Creating a simple project in Delphi.
Welcome to the third chapter of the FREE online programming
course:
A Beginners Guide to Delphi Programming.
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.
Creating your first 'Hello World' Delphi Application
It's time to create a simple example in Delphi now. When you start
Delphi, a default project is created with one form. This default
project automatically creates a blank form, with its associated unit
file and a project file, among others.
To get started, from the beginning, close anything that's open by
choosing File | Close All from the main menu.

More of this Feature


Page 2: Writing and
compiling code
Page 3: Saving your
work, geting help
Join the Discussion
"Post your views and
comments to this
chapter of the free
Delphi Programming
Course"
Discuss!

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.

Application vs. CLX Application


With some versions of Delphi (supposed Delphi 6 Professional or Enterprise), you can build and
develop cross platform applications that can be ported to Linux and compiled with Kylix. To
develop a CLX application, instead of standard Windows application, you could pick CLX
Application from the File | New menu. The Delphi IDE is similar to one when you build Windows
applications, except that the Component palette changes dynamically to show the objects that
are available for use in Linux CLX applications.
Since this course is about Delphi for the Windows platform, we will be exploring Delphi
programming from that point of view. However, if you have Kylix and want to join this course
you are of course encouraged to do so. Even though, my intention at this stage of this Course, is
not to explain differences between CLX (Linux) and VCL (Windows) development you should
know that there are no reasons why you should not join the course and just have in mind that
when we talk about, let's say, form1.DFM you think form1.XFM.
Page 2: Writing code, compiling and running your application for the first time.
Hello Delphi
Now that we've created a project, we can begin work on our first
application. This first application will be pretty simple - we'll change
the caption of the (main) form once the application is executed. The
change will be initiated from code - no user interaction will be
necessary.

More of this Feature


Page 1: Creating a
project
Page 3: Saving your
work, geting help

Join the Discussion


To add the code that changes the caption of the form we need to
"Post your views and
*call* the Code Editor window. If you have the Project Manager
comments to this
displayed on the screen, double click the Form1. This will bring up
chapter of the free
the Form designer window to the front. Another way to bring the
Delphi Programming
Form1 to the front of the screen is to select Form1 from the Window Course"
menu. Once Form1 is on top and active, double click it. This action
Discuss!
has the following result: the Code editor is positioned on the top of
Related Resources
the screen and Delphi creates the skeleton code for the new event
A Beginner's Guide to
handler.
Note: another way of achieving the same result is to activate Form1 Delphi
in the Object Inspector, select the Events tab and double click in the Programming.TOC
OnCreate column value.
As stated in the second chapter of this course, each form has a collection of events such as a
mouse click, keypress, or component activation for which you can specify some additional
behavior. In this case the event is called OnCreate. This event occurs when the form is created.
The skeleton code looks like:
procedure TForm1.FormCreate(Sender: TObject);
begin
//this is where your code goes

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

More of this Feature


Page 1: Creating a
project
Page 2: Writing and
compiling code
Printer friendly version
Join the Discussion
"Post your views and
comments to this
chapter of the free
Delphi Programming
Course"
Discuss!

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.

More of this Feature


Page 2: Properties and
Event Handlers

Join the Discussion


"Post your views and
comments to this
Creating your second Delphi Application
chapter of the free
In the previous chapter we have created a simple Delphi application Delphi Programming
without going into details of the Object Pascal language behind all
Course"
Delphi projects. This time, our task is to create a more complex
Discuss!
application that involves several Delphi components - again, the
application will be pretty simple. The idea is to help you understand Related Resources
A Beginner's Guide to
the Delphi Pascal source and how components operate and
Delphi
communicate with their properties, methods and events.
Programming.TOC
To start, run Delphi. As explained, when you run Delphi a new
project (application) is created with one blank form.

Placing Components on a Form


All forms of a Delphi application have one or more components. Components, or objects,
usually display information or allow the user to perform an action. For example a Label is used
to display static text, an Edit box is used to allow user to input some data, a Button can be used
to initiate actions.
Any combination of components can be placed on a form, you should remember that Windows
is even-driven, while your application is running a user can interact with any component on a
form, it is your task, as a programmer, to decide what happens when a user clicks a button or
changes a text in an Edit box.
As stated before, Delphi supplies a number of components for you to create complex user
interfaces. You can find all the components you can place on a form on the Component palette.
To place a component on a form, locate its icon on the Palette and double-click it. This action
places a component on the active form. Visual representation of most components is set with
their set of properties. When you first place a component on a form, it is placed in a default
position, with default width and height. You can change the size and position later, by using the
Object Inspector.
Note: to remove a component from a form, click on it and press the [Del] key. Later, in this
Course, I'll explain what happens to code (if some exists) associated with the component.
Your second Delphi application
We can now start adding components to a form. Activate the only form in a project, point to
the Component palette and select the "Standard" tab. We will add three standard Windows
components and write some example code to see how components work together.

Double click the following three components:


TLabel : use this component when you want to add some text to a form that the user can't
edit.
TEdit : standard Windows edit control. Edit controls are used to retrieve text that users type.
TButton : use this component to put a standard push button on a form.
Using drag-and-drop to rearrange the components to appear on a form similar to:

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.

More of this Feature


Page 1: Placing
Components on a Form
Printer friendly version
Join the Discussion
"Post your views and
comments to this
chapter of the free
Delphi Programming
Course"
Discuss!

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

'Hello...' (of course without the single quotation marks)

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!

More of this Feature


Page 2: Keywords

Join the Discussion


"Post your views and
comments to this
chapter of the free
Delphi Programming
Understanding the unit source
Course"
In the previous chapter you have created your second simple Delphi Discuss!
application without going into details about the Delphi Pascal
Related Resources
keywords that appear in each Delphi unit. This time, our task is to
take a look at exactly what each keyword means by examining each A Beginner's Guide to
Delphi
line of the forms unit source code.
Programming.TOC
As you know already by now, forms are visible building blocks of all Project Unit
(well, at least 99%) Delphi projects. Each form in a Delphi project has Unit Sections
an associated unit. The unit contains the source code for any event TForm:
Birth/Life/Death
handlers attached to the events of the form or the components it
contains.
The best way to describe the unit code is to take a look at the source. For the moment reefer to
the example in the last chapter, especially the unit source. After we have placed a Label, an Edit
box and a Button, and added an OnClick event handling procedure for the button, the source

code looked like:


01: unit Unit1;
02: interface
03: uses
03: Windows, Messages, SysUtils, Variants, Classes,
03: Graphics, Controls, Forms, Dialogs, StdCtrls;
04: type
05: TForm1 = class(TForm)
06: Edit1: TEdit;
07: Button1: TButton;
08: Label1: TLabel;
09: procedure Button1Click(Sender: TObject);
10: private
11: { Private declarations }
12: public
13: { Public declarations }
14: end;
15: var
16: Form1: TForm1;
17: implementation
18: {$R *.dfm}
19: procedure TForm1.Button1Click(Sender: TObject);
20: var s: string;
21: begin
22: s := 'Hello ' + Edit1.Text + ' Delphi welcomes you!';
23: ShowMessage(s);
24: end;
25: end.
We'll now explore and try to figure what each line stands for. First, a note: Delphi units follow a
predefined format. For example, the UNIT keyword must be the first line in the source,
followed by INTERFACE... This strict format is "predefined" by Delphi, meaning that when you
add an empty form to a project, its associated unit source is already created with special
keywords and type declaration. When you add a component on a form and write an event
handler for it, Delphi will place the corresponding code at the exact location in the unit file.

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.

More of this Feature


Page 1: Unit source

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.

Join the Discussion


"Post your views and
comments to this
chapter of the free
Delphi Programming
Course"
Discuss!

Printer friendly version

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.

The TForm1 is a class inherited from TForm (line 05).


Each component dropped on a form becomes a field (or variable) of the TForm1 class (lines 06
through 08). For example, Edit1 is a variable of a TEdit type, which you see on the screen when
you run the program. When you need to read a value from this particular edit box you use the
Edit1 variable, like in 's := Edit1.Text'.
Each event handling procedure for a form events or events for components dropped on a form
(form fields) will have its declaration (line 09) in the interface type part.
For an explanation on private and public parts (lines 10 through 14) of a class declaration,
please refer to Hiding Data, a part of the Creating Custom Delphi Components - Inside and Out
article.

The INTERFACE VAR section


This part (line 15,16) of the interface section is used to declare (create) a Form1 object as an
instance of the TForm1 class. If you have created your own data type (with fields, properties
and methods) as a part of this unit, you could create a variable of that type in this part of the
interface section.
The IMPLEMENTATION section
The implementation section is defined as everything between the implementation word and
either the initialization statement or the end of the file (as denoted by the end. keyword).
The implementation is where you write code that performs actions. This section is private to
the unit, and can contain both declarations and code. The implementation section of a unit can
contain its own uses clause as well.
A few words on using another unit (form)
As you will see in the following chapters of this course, a (form) unit can use another unit.
Simply put, this means that one form can call another form. Suppose you have a main form
(form name: MainForm, unit name: MainFormUnit) in a project with an 'About...' button on it.
What you want to do is to show an about box form (form name: AboutForm, unit name:
AboutFormUnit) when you click on this button. To be able to do this the MainFormUnit must
use the AboutFormUnit, the AboutFormUnit should be placed in the implementation uses
clause.
To actually call a method (procedure or function) from MainFormUnit that is declared in the
AboutFormUnit, you use the following syntax:
AboutFormUnit.SomeProcedureName(parameters)
Note that the call to a procedure SomeProcedureName consists of a unit name
(AboutFormUnit) followed by a period (.) and a procedure name. This fact is very important. If
in some stage of the development of your project you decide to save AboutFormUnit under a
different name - you will need to change the call to any procedure inside that unit, since the
name of the unit will no longer be AboutFormUnit. This is the reason why you should give
meaningful name to units in the early stage of form (unit) development.

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.

Scope of Variables and Constants


The term scope refers to the availability of a variable or constant declared (or used) in one part
of a program to other parts of a program.
Unless we specify otherwise, changing the value of a variable named, let's say, SomeNumber in
one procedure (function) will not affect another variable with the same name in another
procedure (function).
Since Delphi requires us to declare variables, it's a lot harder to fall into the trap caused by side
effects accidentally. As we know by now, every variable used in some procedure has to be
declared in the var section of the event handler.
In general, we declare a variable where we want to use it. For example, if we want to use a
variable in an event handler, we declare the variable within the event handler.
Local Scope (+ variable declaration and initialization)
Most variables have local scope, which means that the variable is visible only within the code
block in which it is declared (usually: Event Handler for some method). In particular, an event
handler will not normally have access to the value of a variable in another event handler.
If we want to be sure a variable is local within an event handler, we have to declare it in the var
section inside the event handler. Since we must declare a variable before we can use it, if we
can use a variable without declaring it locally, we know that there is a variable with greater
scope with the same name somewhere around project.
Let us look at the first example:
1. Start Delphi, this will give us (by default) new application with one blank form.
2. Double click somewhere on the form (to create OnCreate event handler)
3. Write down this code:
procedure TForm1.FormCreate(Sender: TObject);
begin
ShowMessage(FloatToStr(SomeNumber));
end;
4. If you try to run your project now, you will be prompted with: "Undeclared Identifier:
'SomeNumber'" error. This means that we haven't declared SomeNumber variable in our
project (note: entire project, not FormCreate event handler).
5. To declare SomeNumber variable as double type change your code to:
procedure TForm1.FormCreate(Sender: TObject);
var SomeNumber: double;
begin
ShowMessage(FloatToStr(SomeNumber));
end;
6. Run your project, message box will appear with some strange (value of the memory region
where variable is stored) number. Delphi will also give us "Variable 'SomeNumber' might not

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.

Let's look at the second example:


0. We will be modifying our first example (be sure to have it)
1. Add declaration of SomeNumber, so that implementation code of the unit looks like:
...
implementation
{$R *.DFM}
var
SomeNumber: Double;
...
2. Run your program. As you can see, we don't have "Undeclared Identifier: 'SomeNumber'"
error in OnClick handler of the TButton. When program starts message box will appear with
123.45 value. When you click on the Button1 message box will display 555.55; that's why we
need step 10 in the first example - we have initialized SomeNumber to 555.55 in the OnClick
event of the Button1.
What's this? We have two SomeNumber variables in our project and they both hold different
values.
Obviously, we have to be careful when assigning values to unit-level variables. Although we can
use the same variable (or constant) name for both local and unit-level variables, this is not a
good idea. Any var (or const) declaration contained in a procedure takes precedence over
global (unit-level) declarations. Duplicating the names makes the global variable invisible to the
procedure (Delphi doesn't tell us whether a global variable has been defined with the same
name as a local variable). That is why SomeNumber holds the 123,45 value in the OnCreate
event handler of the form (we cannot use global variable SomeNumber in the OnCreate
procedure)
Note 1: If you really have to use two variables with the same SomeNumber name (one global
and one local), you can access the global SomeNumber variable value in the forms OnCreate
procedure with the call to unit1. SomeNumber (unit1 is the name of the unit with the global
SomeNumber variable). That is, something like
unit1.SomeNumber:=444.44;
will change value of the global variable SomeNumber inside OnCreate event handler of the
form (remember that there is a SomeNumber variable local to this procedure which will stay
unchanged)
Note 2: As global SomeNumber is global to the unit we can access (more important: change) its
value from any other procedure inside this unit. However click to Button 1 will reset
SomeNumber value to 555.55. Better way to initialize global variables is inside initialization
section of the unit.

Global variables - program level scope


If we want to create true global variables (or/and constants) in a project, we have to place the
declaration in the interface section of the unit. Variables declared in the interface section will
be visible (accessible) to any unit which uses that unit.
For example, to change SomeNumber variable value that is declared in Unit1 from Unit2, use
this statement:
Unit1.SomeNumber:=999.99;
Be sure to add Unit1 to the uses clause of Unit2.
Conclusion
That's it. I hope you have had the power to come to the end of this article. As we can see, there
is much to be stated about variable scope in Object Pascal. Of course, there is more: static
variables (or typed constants) are something we could name "constant variables". I'll be dealing
with static variables in some of the future articles...
When Delphi invokes an event handler, the old values of local variables are wiped out. What if
we want to keep track of how many times a button has been clicked? We could have the values
persist by using a unit-level variable, but it is generally a good idea to reserve unit-level
variables only for sharing information. What we need are usually called static variables or typed
constants in Delphi.
Variable or constant?
Typed constants can be compared to initialized variables-variables whose values are defined on
entry to their block (usually event handler). Such a variable is initialized only when the program
starts running. After that, the value of a typed constant persists between successive calls to
their procedures.
Using typed constants is a very clean way of implementing automatically initialized variables. To
implement these variables without typed constants, we'll need to create an initialization
section that sets the value of each initialized variable.
Variable typed constants
Although we declare typed constants in the const section of a procedure, it is important to
remember that they are not constants. At any point in your application, if you have access to
the identifier for a typed constant you'll be able to modify its value.
To see typed constants at work, put a button on a blank form, and assign the following code to
the OnClick event handler:
procedure TForm1.Button1Click(Sender: TObject) ;

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

f language = Delphi then


begin
Use(language)
end
else
Skip(language) ;
Branching
If you want to control the flow of code execution depending on what the program has already
done or what it has just encountered you need to use one of the two Delphi Pascal branching
statements: if statements and case statements.
The IF THEN ELSE statement
The if statement is used to test for a condition and then execute sections of code based on
whether that condition is True or False. The condition is described with a Boolean expression, If
the condition is True, the code flow branches one way. If the condition is False, the flow
branches in another direction. Let's see this behavior on an example:
var iNumber : Integer;
begin
//some value must be
//assigned to iNumber here!
if iNumber = 0 then
ShowMessage('Zero value encountered!') ;
end;
If the number (assigned to iNumber variable) is 0, the expression iNumber = 0 evaluates to True
and the message is displayed; otherwise, nothing is displayed.
continue reading below our video
The Most Popular Camera Apps
Play
0:00
/
0:00
Fullscreen
If we want more than one thing to happen when the tested condition is True, we can write
multiple statements in a begin ... end block.
var iNumber : Integer;
begin
//some value must be
//assigned to iNumber here!

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

//no need to use begin-end here


if iNumber < 0 then
ShowMessage('Your number is negative!')
else
ShowMessage('Your number is positive!') ;
end;
Note: When you write nested if statements choose a consistent, clear indentation style. This
will help you and anyone else who reads your code see the logic of the if statement and how
the code flows when your application runs.
The CASE statement
Although, we can use the if statement for very complex (nested) condition testing, the case
statement is usually easier to read (debug!) and the code runs more quickly.
The case statement makes it clear that a program has reached a point with many branches;
multiple if-then statements do not.
var
iNumber : Integer;
begin
//some value must be
//assigned to iNumber here!
case iNumber of
0 : ShowMessage('Zero value') ;
1..10 : ShowMessage('Less than 11, greater than 0') ;
-1, -2, -3 : ShowMessage('Number is -1 or -2 or -3') ;
else
ShowMessage('I do not care') ;
end;
end;
What follows the case keyword is usually called the selector. The selector is a variable or
expression taken from either the char type or any integer type (an ordinal type). String type are
invalid!. However, the StringToCaseSelect custom function enables you to use the Case
statement with string type variables
As you can see, the individual case statements use a single constant, a group of constants
(separated by comma), or a range of constants (double dot separated). We can even add an
else keyword to take care of all the remaining cases at once.
Note 1: Only one case statement will be executed, we cannot have overlapping conditions in
the case statements.

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.

You might also like