Delphi Cookbook - Second Edition.pdf

DownLoad Book

Published: 2018-04-09 Author:Bieber 22 Browses

Tags: delphi


Extracting password:5f734bfc7ca193aa

Delphi Cookbook
Second Edition
Over 60 hands-on recipes to help you master the power
of Delphi for cross-platform and mobile development on
multiple platforms
Daniele Teti
Delphi Cookbook
Second Edition
Copyright © 2016 Packt Publishing
All rights reserved. No part of this book may be reproduced, stored in a retrieval system, or
transmitted in any form or by any means, without the prior written permission of the publisher,
except in the case of brief quotations embedded in critical articles or reviews.
Every effort has been made in the preparation of this book to ensure the accuracy of the
information presented. However, the information contained in this book is sold without
warranty, either express or implied. Neither the author, nor Packt Publishing, and its dealers
and distributors will be held liable for any damages caused or alleged to be caused directly or
indirectly by this book.
Packt Publishing has endeavored to provide trademark information about all of the companies
and products mentioned in this book by the appropriate use of capitals. However, Packt
Publishing cannot guarantee the accuracy of this information.
First published: September 2014
Second edition: June 2016
Production reference: 1280616
Published by Packt Publishing Ltd.
Livery Place
35 Livery Street
Birmingham B3 2PB, UK.
ISBN 978-1-78528-742-8
Daniele Teti
Roman Yankovsky
Commissioning Editor
Priya Singh
Acquisition Editor
Rahul Nair
Content Development Editor
Deepti Thore
Technical Editor
Mohita Vyas
Copy Editor
Merilyn Periera
Project Coordinator
Shweta H. Birwatkar
Sas Editing
Monica Ajmera Mehta
Disha Haria
Production Coordinator
Arvindkumar Gupta
Cover Work
Arvindkumar Gupta
About the Author
Daniele Teti is a software architect, trainer, and consultant with over 20 years of
professional experience. He writes code in a number of languages but his preferred
language for compiled native software, is Object Pascal.
Daniele is an Embarcadero MVP and is a well known Delphi and programming expert in
the developers' community. He's the main developer and drives the development of some
Delphi open source projects (DelphiMVCFramework, LoggerPro, DORM—"The Delphi ORM",
Delphi Redis Client, Delphi STOMP Client, and so on). After writing some articles for the most
important programming magazines in Italy and a number of on-line publications, Daniele
started to write books. His Delphi Cookbook, published in late 2014, has been a bestseller.
Daniele wrote his rst program when he was 11 year old, and since then happily continues to
write software almost every day. Apart from Delphi, he's a huge fan of design patterns, open
source, distributed architectures, RESTful architectures, and Android OS. Daniele has been
the project manager for a lot of big projects in Italy and in Europe, for private companies and
public institutions. When is not busy writing software or writing about programming (for a job
or for a hobby), he like to play guitar, write songs, and do voluntary activities. Currently he
is CEO of BIT Time Professionals, an Italian company specializing in high level consultancy,
training, and development. The company specializes in high performance software, web and
mobile solutions, and distributed architecture. Bit Time Professionals is also an Italian leader
about indoor proximity solutions using beacon technology, where it provides solutions for
museums, supermarkets, art galleries, fairs, and events in general.
Daniele acts as a consultant and teacher for many Italian and European companies, so he
travels very often around the world.
Daniele is the technical director for the ITDevCon conference, the biggest European
Delphi conference ( He's also an international speaker at technical
Daniele lives in Rome, Italy, with his beloved wife Debora and their little boy Mattia.
Thank you to my wife Debora and my son Mattia.
About the Reviewer
Roman Yankovsky is a long time Delphi developer who has been working with Delphi
since Delphi 2. He has developed and maintained various applications in different industries.
Currently he is working with ShareBike, developing a public bike sharing system. Roman is an
Embarcadero MVP and a frequent speaker at developer conferences. Most recently, his focus
is on the development of productivity tools for developers. He is the author of the FixInsight
static analysis tool for Delphi.
eBooks, discount offers, and more
Did you know that Packt offers eBook versions of every book published, with PDF and ePub
les available? You can upgrade to the eBook version at and as a print
book customer, you are entitled to a discount on the eBook copy. Get in touch with us at for more details.
At, you can also read a collection of free technical articles, sign up for
a range of free newsletters and receive exclusive discounts and offers on Packt books and
Do you need instant solutions to your IT questions? PacktLib is Packt's online digital book
library. Here, you can search, access, and read Packt's entire library of books.
Why Subscribe?
f Fully searchable across every book published by Packt
f Copy and paste, print, and bookmark content
f On demand and accessible via a web browser
Table of Contents
Preface v
Chapter 1: Delphi Basics 1
Introduction 1
Changing your application look and feel with VCL styles and no code 2
Changing the style of your VCL application at runtime 5
Customizing TDBGrid 9
Using owner draw combos and listboxes 16
Making an owner draw control aware of the VCL styles 19
Creating a stack of embedded forms 25
Manipulating JSON 28
Manipulating and transforming XML documents 34
I/O in the 21st century – knowing the streams 44
Creating a Windows service 47
Associating a le extension with your application on Windows 52
Be coherent with the Windows look and feel using TTaskDialog 58
Chapter 2: Becoming a Delphi Language Ninja 71
Introduction 71
Fun with anonymous methods – using higher-order functions 72
Writing enumerable types 76
RTTI to the rescue – conguring your class at runtime 80
Duck typing using RTTI 84
Creating helpers for your classes 88
Chapter 3: Knowing Your Friends – the Delphi RTL 99
Introduction 99
Check strings with regular expressions 100
Consuming RESTful services using native HTTP(S) client libraries 106
Cope with the encoded Internet world using System.NetEncodings 119
Table of Contents
Save space using System.Zip 126
Decouple your code using a cross-platform publish/subscribe mechanism 129
Chapter 4: Going Cross-Platform with FireMonkey 137
Introduction 137
Giving a new appearance to the standard FireMonkey controls using styles 138
Creating a styled TListBox 144
Impressing your clients with animations 149
Using master/details with LiveBindings 153
Showing complex vector shapes using paths 165
Using FireMonkey in a VCL application 170
Reinventing your GUI also known as 177
mastering Firemonkey controls, shapes, and effects 177
Chapter 5: The Thousand Faces of Multithreading 187
Introduction 187
Synchronizing shared resources with TMonitor 188
Talking with the main thread using a thread-safe queue 196
Synchronizing multiple threads using TEvent 199
Displaying a measure on a 2D graph like an oscilloscope 203
Using tasks to make your customer happier 208
Monitoring things using futures 216
Parallelize using the parallel for 222
Chapter 6: Putting Delphi on the Server 231
Introduction 231
Developing web client JavaScript applications with WebBroker on the server 232
Converting a console application to a Windows service 242
Serializing a dataset to JSON and back 245
Serializing objects to JSON and back using RTTI 250
Sending a POST HTTP request encoding parameters 256
Implementing a RESTful interface using WebBroker 260
Controlling remote application using UDP 277
Using app tethering to create a companion app 283
Creating DataSnap Apache modules 290
Creating WebBroker Apache modules 301
Using native HTTP(S) client libraries 308
Chapter 7: Riding the Mobile Revolution with FireMonkey 321
Introduction 322
Taking a photo, applying effects, and sharing it 322
Using TListView to show and search local data 331
Using SQLite databases to handle a to-do list 339
Do not block the main thread! 344
Table of Contents
Using a styled TListView to handle long lists of data 352
Customizing the TListView 362
Taking a photo and location and sending it to a server continuously 372
Talking with the backend 382
Making a phone call from your app! 390
Tracking the application's lifecycle 395
Chapter 8: Using Specic Platform Features 401
Introduction 401
Using Android SDK Java classes 402
Using iOS Objective C SDK classes 408
Displaying PDF les in your app 412
Sending Android Intents 418
Letting your phone talk – using the Android TextToSpeech engine 426
Using Java classes in Android apps with Java2OP 430
Doing it in the background, the right way – Android services 433
Index 447
If you've been a software developer for a long time, you certainly know how useful a
conversation can be with a colleague who has already done something similar to what you
are doing and can explain it, as they faced the same problem. It is not possible to put all
the possible situations that a developer can face in a book, but many problems are similar
at least in principle. This is the reason this book is organized as a cookbook: just like a
combination of foods can be adapted and modied to be appropriate for different types of
dinner, a "programming recipe" can provide the idea to solve many different problems.
This book is an advanced level guide that will help Delphi developers get a higher expertise in
their everyday job. The everyday job, and the quality of your deliverables, is what contributes
to the quality of your professional life. If it does not make sense, reinvent the wheel
repeatedly, especially when working with a well-established tool, such as Delphi. The focus of
the book is to provide readers with comprehensive and detailed examples on how effectively
the Delphi software can be designed and written. All the recipes in the book are the result
of years of development, training, and consultancy activities in many different elds of the
IT industries, from the small systems with thousands of installations to the large systems
commissioned by big companies or by the government. It is not a magic book that will solve
all your development problems (if you nd it, tell me, please!), but can be helpful to get a
different point of view on a specic problem, or a hint on how to solve problems.
Armed with the knowledge of advanced concepts, such as high order functions and
anonymous methods, generics and enumerable, extended RTTI and duck typing, LiveBindings,
multi-threading, FireMonkey, mobile development, server-side development, and so on, you
will be pleasantly surprised as to how quickly and easily you can use Delphi to write high
quality, clean, readable, fast, maintainable, and extensible code.
I read too many boring programming books, so I tried to maintain a relaxed and light
exposition. A small applicability scenario that describes a situation where a particular
technology, approach, or design pattern can be used successfully introduces all the recipes.
The recipes are not too complex, because otherwise the book may become thousands of
pages long, but also not trivial because the IT books' landscape is already full of simple
examples with few direct applicability. I tried to do a good tradeoff and I hope to be able
to do it.
Every time I start to read a new book, I ask myself, "Will the author have something interesting
to say?", "How much will this book change my point of view about the topics mentioned?",
"Is it worth the time spent to read it?" Now, in spite of being from the other side of the river,
I worked hard to put as much good quality contents in my books as possible, I hope that will
match your expectations.
One last note. Writing hundreds of pages about advanced programming is not an easy task.
However, I am very pleased to have done it and I hope you will enjoy reading it at least how
I enjoyed writing it.
What this book covers
Chapter 1, Delphi Basics, talks about a set of general approaches that should not be ignored
by any Delphi programmer. Some topics are simple and immediate and some are not but all of
them should be well understood. By the end of this chapter, the reader is able to use some of
the fundamental Delphi techniques related to the RTL, to the VCL, and to the OS integration.
Chapter 2, Becoming a Delphi Language Ninja, focuses on the Object Pascal language. The
programming language is the way you talk to the machine, so you must be uent and know all
the possibilities offered. This chapter talks about higher-order functions, practical utilization of
the extended RTTI, regular expressions, and other things useful to augment the power of your
code and to lower the amount of time spent on debugging.
Chapter 3, Knowing Your Friends – the Delphi RTL, focuses on the Delphi' RTL. There isn't a
detailed description of all the Delphi's RTLs (you would need 10 books like this one, which will
be particularly boring, I guess) but you can nd some recipes that explain some of the most
important RTL features and some less know but really useful classes. You'll learn how to use
regular expressions, the most popular encoding format used by HTTP base applications, and
how to use the built-in data de/compression-related classes.
Chapter 4, Going Cross-Platform with FireMonkey, is dedicated to the FireMonkey framework
in general. What you will learn from this chapter can be used in many of the platforms that
FireMonkey supports. Moreover, you will learn about non-trivial LiveBindings utilizations.
Chapter 5, The Thousand Faces of Multithreading, talks about thread synchronization and the
mechanisms used to obtain this synchronization, such as TMonitor, thread-safe queues, and
TEvent. It is also one of the most complex chapters. By the end of this chapter, the reader will
be able to create and communicate with background threads, leaving your main thread free to
update your GUI (or to communicate with the OS).
Chapter 6, Putting Delphi on the Server, focuses on how well Delphi can behave when running
on a server. Some people think that Delphi is a client-only tool, but it is not true. In this
chapter, we'll show how to create powerful servers that offer services over a network. Then, in
some recipe, we'll also implement a JavaScript client that brings the database data into the
user browser. Techniques explained in this chapter open a range of possibilities, especially in
the mobile and web area.
Chapter 7, Riding the Mobile Revolution with FireMonkey, is dedicated to the mobile
development with Delphi and FireMonkey. If you are interested in mobile development, I think
that will be your favorite chapter! Mobile is everywhere, and this chapter will explain how to
write software for your Android or iOS device, what are the best practices to use, how to save
your data on the mobile, how to retrieve and update remote data, and how to integrate with
the mobile operating system.
Chapter 8, Using Specic Platform Features, shows you how to integrate your app with the
underlying mobile operating systems beyond what FireMonkey offers. You will learn how to
import Java and Objective C libraries in your app and how to use the SDK classes from your
Object Pascal code.
What you need for this book
This book talks about Delphi, so you need it. Not all the recipes are available in all the Delphi
editions. Typically, the mobile projects can be compiled only if you have Delphi Enterprise or
higher (or Delphi Professional plus the mobile add-on, or RAD Studio professional or higher).
All the projects are compiled and tested with the latest Delphi version at the time of writing,
but many recipes can be compiled also on older versions.
If you want to run the mobile app on a phone or a tablet, you could use the Android emulator
or the iOS simulator, but we strongly suggest an actual device to see how the app really
behaves. To deploy an iOS app on your device, you also need an Apple computer with MacOSX.
Who this book is for
This book aims to help the professional Delphi developers in their day-to-day job. This book
will teach you about the newest Delphi technologies and its hidden gems. It is not a book for
a newbie, but the practical approach will help you reach a new level with your Delphi skills.
The experienced developer can benet from this book because nontrivial problems are solved
using best practices. Where more than one way is available or the topic is too broad to be
explained in the available pages, references are provided to allow you to go deeper in that
eld. It is a book to have on your desk for the next few years.
In this book, you will nd a number of styles of text that distinguish between different kinds of
information. Here are some examples of these styles, and an explanation of their meaning.
Code words in text, database table names, folder names, lenames, le extensions,
pathnames, dummy URLs, user input, and Twitter handles are shown as follows: "Style
manipulation at runtime is done using the class methods of the TStyleManager class."
A block of code is set as follows:
procedure TMainForm.StylesListRefresh;
stylename: string;
// retrieve all the styles linked in the executable
for stylename in TStyleManager.StyleNames do
When we wish to draw your attention to a particular part of a code block, the relevant lines or
items are set in bold:
Application.MainFormOnTaskbar := True;
TStyleManager.TrySetStyle('Iceberg Classico');
Application.CreateForm(TMainForm, MainForm);
Any command-line input or output is written as follows:
# cp /usr/src/asterisk-addons/configs/cdr_mysql.conf.sample
New terms and important words are shown in bold. Words that you see on the screen, in
menus or dialog boxes for example, appear in the text like this: "Add all the columns to
TDBGrid by right-clicking and selecting Columns Editor".
Warnings or important notes appear in a box like this.
Tips and tricks appear like this.
Reader feedback
Feedback from our readers is always welcome. Let us know what you think about this book—
what you liked or disliked. Reader feedback is important for us as it helps us develop titles
that you will really get the most out of.
To send us general feedback, simply e-mail, and mention the
book's title in the subject of your message.
If there is a topic that you have expertise in and you are interested in either writing or
contributing to a book, see our author guide at
Customer support
Now that you are the proud owner of a Packt book, we have a number of things to help you to
get the most from your purchase.
Downloading the example code
You can download the example code les for this book from your account at http://
. If you purchased this book elsewhere, you can visit http://www.
and register to have the les e-mailed directly to you.
You can download the code les by following these steps:
1. Log in or register to our website using your e-mail address and password.
2. Hover the mouse pointer on the SUPPORT tab at the top.
3. Click on Code Downloads & Errata.
4. Enter the name of the book in the Search box.
5. Select the book for which you're looking to download the code les.
6. Choose from the drop-down menu where you purchased this book from.
7. Click on Code Download.
You can also download the code les by clicking on the Code Files button on the book's
webpage at the Packt Publishing website. This page can be accessed by entering the book's
name in the Search box. Please note that you need to be logged in to your Packt account.
Once the le is downloaded, please make sure that you unzip or extract the folder using the
latest version of:
f WinRAR / 7-Zip for Windows
f Zipeg / iZip / UnRarX for Mac
f 7-Zip / PeaZip for Linux
The code bundle for the book is also hosted on GitHub at
. We also have other code
bundles from our rich catalog of books and videos available at
. Check them out!
Although we have taken every care to ensure the accuracy of our content, mistakes do happen.
If you nd a mistake in one of our books—maybe a mistake in the text or the code—we would be
grateful if you could report this to us. By doing so, you can save other readers from frustration
and help us improve subsequent versions of this book. If you nd any errata, please report
them by visiting, selecting your book,
clicking on the Errata Submission Form link, and entering the details of your errata. Once your
errata are veried, your submission will be accepted and the errata will be uploaded to our
website or added to any list of existing errata under the Errata section of that title.
To view the previously submitted errata, go to
and enter the name of the book in the search eld. The required
information will appear under the Errata section.
Piracy of copyrighted material on the Internet is an ongoing problem across all media. At
Packt, we take the protection of our copyright and licenses very seriously. If you come across
any illegal copies of our works in any form on the Internet, please provide us with the location
address or website name immediately so that we can pursue a remedy.
Please contact us at with a link to the suspected pirated material.
We appreciate your help in protecting our authors and our ability to bring you valuable content.
If you have a problem with any aspect of this book, you can contact us at questions@
, and we will do our best to address the problem.
Delphi Basics
In this chapter, we will cover the following topics:
f Changing your application's look and feel with the VCL style and without any code
f Changing the style of your application at runtime
f Customizing TDBGrid
f Using owner draw combos and listboxes
f Making an owner draw control aware of the VCL styles
f Creating a stack of embedded forms
f Manipulating JSON
f Manipulating and transforming XML documents
f I/O in the 21st century – knowing the streams
f Creating a Windows service
f Associating a le extension with your application on Windows
f Being coherent with the Windows look and feel using TTaskDialog
This chapter will explain some of the day-to-day needs of a Delphi programmer. These are
ready-to-use recipes that will be useful every day and have been selected ahead of a lot of
others because, although they may be obvious for some experienced users, they are still very
useful. Even if there isn't specically database-related code, many of the recipes can also be
used (or sometimes, especially used) when you are dealing with data.
Delphi Basics
Changing your application look and feel with
VCL styles and no code
Visual Component Library (VCL) styles are a major new entry in the latest versions of Delphi.
They have been introduced in Delphi XE2 and are still one of the lesser known features for
the good old Delphi developers. However, as usual, some businessmen say "looks matter"
so the look and feel of your application could be one of the reasons to choose one product
over another from a competitor. Consider that with a few mouse clicks, you can apply many
different styles to your application to change the look and feel of your applications. So, why
not to give it a try?
Getting ready
VCL styles can be used to revamp an old application or to create a new one with a
non-standard GUI. VCL styles are a completely different beast to FireMonkey styles.
They are both styles, but with completely different approaches and behavior.
To get started with VCL styles, we'll use a new application. So, let's create a new VCL
application and drag and drop some components onto the main form (for example, two
TButton, one TListBox, one TComboBox, and a couple of TCheckBox).
You can now see the resultant form that is running on my Windows 8.1 machine:
Figure 1.1: A form without style
Chapter 1
How to do it…
Now, we've got to apply a set of nice styles by following these steps:
1. Go to Project | Options from the menu. Then, in the resultant dialog, go to
Application | Appearance and select all the styles that we want to include
in our application.
2. Using the Preview button, the IDE shows a simple demo form with some controls, and
we can get an idea about the nal result of our styled form. Feel free to experiment
and choose the style—or set of styles—that you like. Only one style at a time will be
used, but we can link the necessary resources into the executable and select the
proper one at runtime.
3. After selecting all the required styles from the list, we've got to select one in the
combo box at the bottom. This style will be the default style for our form and will be
loaded as soon as the application starts. You can delay this choice and make it at
runtime using code if you prefer.
4. Click on OK, hit F9 (or go to Run | Run), and your application is styled:
Figure 1.2: The same form as Figure 1.1 but with the Iceberg Classico style applied
Delphi Basics
How it works…
Selecting one or more styles from Project | Options | Application | Appearance will cause
the Delphi linker to link the style resource into your executable. It is possible to link many
styles into your executable, but you can use only one style at a time. So, how does Delphi
know which style you want to use when there are more than one? If you check the Project le
(the le with the .dpr extension) by going to Project | View Source Menu, you can see where
and how this little magic happens.
The following lines are the interesting section:
Application.MainFormOnTaskbar := True;
TStyleManager.TrySetStyle('Iceberg Classico');
Application.CreateForm(TMainForm, MainForm);
When we've selected the Iceberg Classico style as the default style, the Delphi IDE added a
line just before the creation of the main form, setting the default style for all the applications
using TStyleManager.TrySetStyle static methods.
TStyleManager is very important class when dealing with VCL styles. We'll see more about it
in the upcoming recipe, where you'll learn how to change styles at runtime.
There's more…
Delphi and C++ Builder 10.1 Berlin come with 36 VCL styles available in the folder (with a
standard installation):
C:\Program Files (x86)\Embarcadero\Studio\18.0\Redist\styles\vcl\
Moreover, it is possible to create your own styles or modify the existing ones using the Bitmap
Style Designer. You can access it by going to Tools | Bitmap Style Designer Menu.
For more details on how to create or customize a VCL style, visit http://docwiki.
The Bitmap Style Designer also provides test applications to test VCL styles.
Chapter 1
Changing the style of your VCL application
at runtime
VCL styles are a powerful way to change the appearance of your application. One of the main
features of VCL styles is the ability to change the style while the application is running.
Getting ready
Because a VCL Style is simply a particular kind of binary le, we can allow our users to load
their preferred styles at runtime. We could even provide new styles by publishing them on a
website or sending them by e-mail to our customers.
In this recipe, we'll change the style while the application is running using a style already
linked at design time, or let the user choose between a set of styles deployed inside a folder.
How to do it…
Style manipulation at runtime is done using the class methods of the TStyleManager class.
Follow these steps to change the style of your VCL application at runtime:
1. Create a brand new VCL application and add the Vcl.Themes and Vcl.Styles
units to the implementation main form uses section. These units are required
to use VCL styles at runtime.
2. Drop on the form a TListBox, two TButton, and a TOpenDialog. Leave the default
component names.
3. Go to Project | Appearance and select eight styles of your choice from the list. Leave
the Default style to Windows.
4. The TStyleManager.StyleNames property contains names of all the available
styles. In the FormCreate event handler, we have to load the already linked styles
present in the executable into the listbox to let the user choose one of them. So,
create a new procedure called StylesListRefresh with the following code and
call it from the FormCreate event handler:
procedure TMainForm.StylesListRefresh;
stylename: string;
// retrieve all the styles linked in the executable
for stylename in TStyleManager.StyleNames do
Delphi Basics
5. In the Button1Click event handler, we've to set the current style according to the
one selected from the ListBox1 using the code as follows:
6. The Button2Click event handler should allow the user to select a style
from the disk. So, we have to create a folder named styles at the level of our
executable and copy a .vsf le from the default style directory, which, in RAD
Studio 10.1 Berlin, is C:\Program Files (x86)\
7. After copying, write the following code under the
Button2Click event handler.
This code allows the user to choose a style le directly from the disk. Then, you can
select one of the loaded styles from the listbox and click on Button1 to apply it to
if OpenDialog1.Execute then
if TStyleManager.IsValidStyle(OpenDialog1.FileName) then
//load the style file
//refresh the list with the currently available styles
ShowMessage('New VCL Style has been loaded');
ShowMessage('The file is not a valid VCL Style!');
8. Just to have an idea of how the different controls appear with the selected style, drag
and drop some controls on the right-hand side of the form. The following image shows
my application with some styles loaded, some at design time and some from the disk.
9. Hit F9 (or go to Run | Run), and play with your application using and loading styles
from the disk:
Chapter 1
Figure 2.1: The Style Chooser form with a Torquoise Gray style loaded
How it works…
The TStyleManager class has all the methods we need to:
f Inspect the loaded styles with TStyleManager.StyleNames
f Apply an already loaded style to the running application using the following code:
f Check whether a le is a valid style using the following code:
f Load a style le from the disk using the following code:
After loading new styles from the disk, the new styles are completely similar to the styles
linked in the executable during the compile and link phases and can be used in the same way.
Delphi Basics
There's more…
Other things to consider are third-party controls. If your application uses third-party controls,
take care with their style support (some third-party controls are not be style aware). If your
external components do not support styles, you will end up with some styled controls (the
original included in Delphi) and some not styled (your external third-party controls)!
Go to Tools | Bitmap Style Designer. Using a custom VCL style we can also:
f Change application colors, such as ButtonNormal, ButtonPressed,
ButtonFocused, ButtonHot, and others
f Override system colors, such as clCaptionText, clBtnFace, clActiveCaption,
and so on
f Font color and font name for particular controls familiar to ButtonTextNormal,
ButtonTextPressed, ButtonTextFocused, ButtonTextHot, and many others
Figure 2.2: The Bitmap Style Designer while it is working on a custom style
Chapter 1
Customizing TDBGrid
The adage "A picture is worth a thousand words" refers to the notion that a complex idea
can be conveyed with just a single still image. Sometimes, even a simple concept is easier
to understand and nicer to see if it is represented by images. In this recipe, we'll see how to
customize TDBGrid to visualize a graphical representation of data.
Getting ready
Many VCL controls are able to delegate their drawing, or part of it, to user code. It means that
we can use simple event handlers to draw standard components in different ways. It is not
always simple, but TDBGrid is customizable in a really easy way. Let's say that we have a class
of musicians that have to pass a set of exams. We want to show the percent of exams already
passed with a progress bar and, if the percent is higher than 50, there should also be a check
in another column. Moreover, after listening to the pieces played at the exams, each musician
received votes from an external examination committee. The last column needs to show the
mean of votes from this committee as a rating from 0 to 5.
How to do it…
We'll use a special in memory table from the FireDAC library. FireDAC is a new data
access library from Embarcadero included in RAD Studio since version XE5. If some of the
code seems unclear at the moment, consider the in-memory table as a normal TDataSet
descendant, which holds its data only in memory. However, at the end of the section, there
are some links to the FireDAC documentation, and I strongly suggest that you read them if you
still don't know FireDAC:
1. Create a brand new VCL application and drop a TFDMemTable, a TDBGrid, a
TDataSource, and a TDBNavigator on the form. Connect all the components in the
usual way (TDBGrid connected to TDataSource followed by TFDMemTable). Set
TDBGrid's font size to 18. This will create more space in the cell for our graphical
2. Using the TFDMemTable elds editor, add the following elds and then activate the
dataset by setting its
Active property to True:
Field name Field data type Field type
FullName String (size 50)
TotalExams Integer
PassedExams Integer
Rating Float
PercPassedExams Float
MoreThan50Percent Boolean
Delphi Basics
3. Now, add all the columns to TDBGrid by right-clicking and selecting Columns Editor.
Then, again right-click and select Add all elds on the resultant window. Then,
rearrange the columns as shown here and give a nice title caption:
4. In a real application, we should load real data from some sort of database. However,
for now, we'll use some custom data generated in code. We have to load this data
into the dataset with the code as follows:
procedure TMainForm.FormCreate(Sender: TObject);
['Ludwig van Beethoven', 30, 10, 4]);
['Johann Sebastian Bach', 24, 10, 2.5]);
['Wolfgang Amadeus Mozart', 30, 30, 5]);
['Giacomo Puccini', 25, 10, 2.2]);
['Antonio Vivaldi', 20, 20, 4.7]);
['Giuseppe Verdi', 30, 5, 5]);
['John Doe', 24, 5, 1.2]);
5. Do you remember? We've two calculated elds that need to be lled in some way.
Calculated elds need a form of processing behind them to work. The TFDMemTable,
just like any other TDataSet descendant, has an event called OnCalcFields
that allows the developer to do so. Create the OnCalcFields event handler on
TFDMemTable and ll it with the following code:
procedure TMainForm.FDMemTable1CalcFields(
DataSet: TDataSet);
LPassedExams: Integer;
LTotExams: Integer;
Chapter 1
LPassedExams := FDMemTable1.
LTotExams := FDMemTable1.
if LTotExams = 0 then
FDMemTable1.FieldByName('PercPassedExams').AsFloat := 0
FDMemTable1.FieldByName('PercPassedExams').AsFloat :=
LPassedExams / LTotExams * 100;
FDMemTable1.FieldByName('MoreThan50Percent').AsBoolean :=
FDMemTable1.FieldByName('PercPassedExams').AsFloat > 50;
6. Run the application by hitting F9 (or by going to Run | Run) and you will get the
following screenshot:
Figure 3.1: A normal form with some data
7. This is useful, but a bit boring. Let's start our customization. Close the application
and return to the Delphi IDE.
8. Go to the Properties of TDBGrid and set Default Drawing to False.
9. Now, we've to organize the resources used to draw the grid cells. Calculated elds will
be drawn directly using code, but the Rating eld will be drawn using a 5-star rating
image from 0 to 5. It starts with a 0.5 incremental step (0, 0.5, 1, 1.5, and so on). So,
drop TImageList on the form, and set Height as 32 and Width as 160.