A Beginner's Guide To Delphi
A Beginner's Guide To Delphi
A Beginner's Guide To Delphi
By Zarko Gajic
Delphi Expert
About Delphi Programming site proudly presents: free online programming courses for
(beginner) Delphi developers!
Quick launch:
Objects that will be instantiated on a different machine across the world if you so
desired.
In 1975, Wirth and Jensen produced the ultimate Pascal reference book "Pascal User Manual
and Report". Wirth stopped its work on Pascal in 1977 to create a new language, Modula the successor to Pascal.
Borland Pascal
With the release (November 1983) of Turbo Pascal 1.0, Borland started its journey into the
world of development environments and tools.
To create Turbo Pascal 1.0 Borland licensed the fast and inexpensive Pascal compiler core,
written by Anders Hejlsberg. Turbo Pascal introduced an Integrated Development
Environment (IDE) where you could edit the code, run the compiler, see the errors, and jump
back to the lines containing those errors. Turbo Pascal compiler has been one of the bestselling series of compilers of all time, and made the language particularly popular on the PC
platform.
In 1995 Borland revived its version of Pascal when it introduced the rapid application
development environment named Delphi - turning Pascal into a visual programming
language. The strategic decision was to make database tools and connectivity a central part
of the new Pascal product.
The roots: Delphi
After the release of Turbo Pascal 1, Anders joined the company as an employee and was the
architect for all versions of the Turbo Pascal compiler and the first three versions of Delphi.
As a chief architect at Borland, Hejlsberg secretly turned Turbo Pascal into an objectoriented application development language, complete with a truly visual environment and
superb database-access features: Delphi.
What follows on the next two pages, is a concise description of Delphi versions and its
history, along with a brief list of features and notes.
Note: some of the links below marked with an asterix (*), using the Internet Archive
WayBackMachine, will take you several years in the past, showing how Delphi site looked
long-ago.
The rest of the links will point you to a more in-depth look at what each (new) technology is
about, with tutorials and articles.
Delphi 1 (1995)
Delphi, Borland's powerful Windows programming development tool first appeared in 1995.
Delphi 1 extended the Borland Pascal language by providing object-orientated and formbased approach, extremely fast native code compiler, visual two-way tools and great
database support, close integration with Windows and the component technology.
Here's the Visual Component Library First Draft
Delphi 1* slogan:
Delphi and Delphi Client/Server are the only development tools that provide the Rapid
Application Development (RAD) benefits of visual component-based design, the power of an
optimizing native code compiler and a scalable client/server solution.
Heres what were the "7 Top Reasons to Buy Borland Delphi 1.0 Client/Server*"
Delphi 2 (1996)
Delphi 2* is the only Rapid Application Development tool that combines the performance of
the world's fastest optimizing 32-bit native-code compiler, the productivity of visual
component-based design, and the flexibility of scalable database architecture in a robust
object-oriented environment.
Delphi 2, beside being developed for the Win32 platform (full Windows 95 support and
integration), brought improved database grid, OLE automation and variant data type
support, the long string data type and Visual Form Inheritance. Delphi 2: "the Ease of VB
with the Power of C++"
Delphi 3 (1997)
The most comprehensive set of visual, high-performance, client and server development tools
for creating distributed enterprise and Web-enabled applications.
Delphi 3* introduced new features and enhancements in the following areas: the code
insight technology, DLL debugging, component templates, the DecisionCube and TeeChart
components, the WebBroker technology, ActiveForms, component packages, and
integration with COM through interfaces.
Delphi 4 (1998)
Delphi 4* is a comprehensive set of professional and client/server development tools for
building high productivity solutions for distributed computing. Delphi provides Java
interoperability, high performance database drivers, CORBA development, and Microsoft
BackOffice support. You've never had a more productive way to customize, manage, visualize
and update data. With Delphi, you deliver robust applications to production, on time and on
budget.
Whats more, Delphi 6 added the support for cross-platform development thus enabling
the same code to be compiled with Delphi (under Windows) and Kylix (under Linux). More
enhancements included: support for Web Services, the DBExpress engine, new components
and classes...
Delphi 7 (2001)
Borland Delphi 7 Studio provides the migration path to Microsoft .NET that developers have
been waiting for. With Delphi, the choices are always yours: you're in control of a complete ebusiness development studio with the freedom to easily take your solutions cross-platform
to Linux.
Delphi 8
For the 8th anniversary of Delphi, Borland prepared the most significant Delphi release:
Delphi 8 continues to provide Visual Component Library (VCL) and Component Library for
Cross-platform (CLX) development for Win32 (and Linux) as well as new features and
continued framework, compiler, IDE, and design time enhancements.
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 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!
Note: In the "Borland Delphi Personal Installer" you'll find several interesting folders. In the
\Documentation folder you'll find three PDF files. Developers Guide, Quick Start and Object
Pascal Language Guide. You'll be using those books frequently. In the \Info\Extras there are
several great tools and components. For example, the \Info\Extras\SendKeys includes two
functions that simulate popular Visual Basic routines: Sendkeys and AppActivate.
Installation
To install Delphi 6 Personal, after you have unpacked the installation files, run
INSTALL.EXE (default location C:\Program Files\Borland Delphi Personal Installer) and
follow the installation instructions.
You are prompted to select a product to install, you only have one choice "Delphi 6":
While the setup runs, you'll need to enter your serial number and the authorization key (the
one you got from Borland in your email box).
designing, developing and running, in source and compiled form, the works which you create
for your own personal Noncommercial Purposes, using the Software ("Works"), subject to the
restrictions in this License Agreement. You may distribute your Works to others. You may not
receive any direct or indirect compensation for the distribution or use of your Works.
After that, you have to pick the Setup Type, choose Typical. This way Delphi 6 Personal will
be installed with the most common options. The next screen prompts you to choose the
Destination folder.
At the end of the installation process, the set-up program will create a sub menu in the
Programs section of the Start menu, leading to the main Delphi 6 Personal program plus some
additional tools.
Note: For a faster access to Delphi, create a shortcut on the Windows Desktop.
Choose Programs | Borland Delphi 6 | Delphi 6 from the Windows Start menu
Choose Run from the Windows Start menu and type Delphi32
Double-click Delphi32.exe in the $(DELPHI)\Bin folder. Where $(DELPHI) if a folder
where Delphi was installed. The default is C:\Program Files\Borland\Delphi6.
Double-click the Delphi icon on the Desktop (if you've created a shortcut)
This will lead you to the Borland web site, where you will need to enter your registration
information. In the last step you'll obtain the Activation Key.
And finally, you have run your copy of Delphi 6 Personal for the first time.
Update Pack
After you've successfully installed Delphi Personal I suggest you to obtain the latest Update.
For the moment, Update Pack 2 is available for registered users (which you are now) from
this page: Delphi 6 Downloads. After installation, proceed to download Delphi Personal
Documentation Update.
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.
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
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.
Note: another way of achieving the same result is to activate Form1 in the Object
Inspector, select the Events tab and double click in the 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.
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
context-sensitive 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.
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.
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.
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;
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-something-
funny 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.
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:
20:
21:
22:
23:
24:
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.
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 File-Save 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.
The INTERFACE section
The interface section of a unit starts with the word interface (line 02) and continues until
the word implementation (line 17). This section is used to declare any public sections of
code that appear in a unit. The entire contents of the interface section, including type,
variable 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
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 File-New ... 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.
Button1Click.