Tải bản đầy đủ

Delphi cookbook

www.it-ebooks.info


www.it-ebooks.info


Delphi Cookbook

50 hands-on recipes to master the power of Delphi for
cross-platform and mobile development on Windows,
Mac OS X, Android, and iOS

Daniele Teti

[PACKT]
PUBLISHING

B I R M I N G HAM - M U M BAI

www.it-ebooks.info



Del p h i Cookbook
Copyright© 2014 Packt Publishing

All rights reserved . No pa rt of this book may be reprod uced , stored i n a retrieva l syste m ,
or tra nsm itted i n a ny form or by any mea ns, without t h e prior written perm ission of the
pu blisher, except i n the case of brief q u otations em bedded i n critica l a rticles or reviews.
Every effort has been made in the prepa ration of this book to ensure the accu racy of the
i nformation presented . However, the i nformation conta i ned in this book is sold without
wa rra nty, either express or i m p l ied . Neither the author, nor Packt Publishi ng, and its
dealers and d istributors wi l l be held l iable fo r a ny d a mages ca used or a l l eged to be
ca used d i rectly or i n d i rectly by this book.
Packt Publ ish i ng has end eavored to provide trademark i nfo rmation about all of the
com pa n ies and prod ucts mentioned in this book by the appropri ate use of ca pita ls.
However, Packt Publishing can n ot gua ra ntee the accu racy of this i nformati o n .

Fi rst p u b l ished : Septe m ber 2014

Prod uction reference: 1190914

Publ ished by Packt Publ ish ing Ltd .
Livery Place
35 Livery Street
B i r m i ngham B3 2PB, U K.
ISBN 978-1-78355-958-9

www . packtpub . com
Cover i mage by J u n aid Shah (j una i dshahl l l@gma i l . com)

www.it-ebooks.info


Credits
Copy Editors

Author

Daniele Teti

Roshni Banerjee


Adithi Shetty

Reviewers

Eric Van Feggelen

Project Coordinator

Leena Purkait

Sherwin John
Olivier Pons

Proofreaders

Jorge H. Rodriguez

Bridget Braund
Paul Hindle

Commissioning Editor

Sam Birch

Amy Johnson

Acquisition Editor

Indexers

Richard Harvey

Monica Ajmera Mehta
Tejal Soni

Content Development Editors

Balaji Naidu
Pooja Nair

Graphics

Valentina D'silva
Abhinash Sahu

Technical Editors

Mrunal Chavan

Production Coordinators

Dennis John

Aparna Bhagat

Edwin Moses

Manu Joseph

Cover Work

Aparna Bhagat

www.it-ebooks.info


About the Author
Daniele Teti is a software a rch itect, tra i ner, and consu lta nt with over 18 yea rs of
professional experience. He writes code in a n u m ber of languages but h is preferred
la nguage to com p i l e native software is Object Pasca l .

Daniele i s a wel l-known Del phi a n d progra m m ing expert i n the developer com m u n ity. He's
the m a i n developer and d rives the development of some Del phi open sou rce projects
(Del phi MVCFramework; DO R M , "the Del phi ORM"; Del phi Red is Client; and so on). He wrote his
fi rst program when he was 11 years old, and si nce then, he happily conti n ues to write software
a l m ost every day. Apa rt from Del p h i , he's a huge fa n of design patterns, expert systems, RESTfu l
a rchitectu res, and And roid OS. When he is not busy writi ng software or progra m m ing (as h is
job or hobby), he l i kes to play the gu itar, write songs, and do vol u nta ry activities. Cu rrently, he
works as an R&D Di rector & Ed ucational at bit Ti me Software (www . bi t t ime . i t), an Italian
representative of Embarcadero Technologies (www embarcade ro . com). He recently beca me
the CEO of bit Time Professiona ls, which is a spi n-off com pa ny of bit Ti me Software; this
com pany specializes i n consultancy, tra i n i ng, and development.
.

Bei ng a softwa re a rch itect, consu lta nt, and teacher for m a ny Ita l i a n and E u ropean com p a n i es,
he travels very often a ro u n d the world . He is the Tec h n ica l Di rector of ITDevCon , the biggest
Europea n Del p h i conference (www . i tdevcon . i t ) . He's a lso a n i nternational spea ker at
m a ny tec h n ical conferences.
Daniele l ives in Rome, Ita ly (where each photogra pher becomes an a rtist) with h is beloved
wife, Debora, and their l ittle boy, Mattia.

www.it-ebooks.info


About the Reviewers
Eric van Feggelen is a passionate a n d experienced softwa re consu lta nt who delivers
h igh-q ual ity sol utions usi ng the latest tech nologies ava i l a ble. He has a bout 15 yea rs of
experience as a developer and has been i nterested in i nformation technology h is enti re l ife.
I n the past few yea rs, he wo rked for major corporations, such as M icrosoft a n d Ava nade
a n d conti n u es to serve the Microsoft Enterprise space as a private contractor for h is own
com pa ny. At the time of writi ng th is book, Eric has worked as a lead d eveloper for a Microsoft
Dyn a m i cs sta rt-up.

I n 2013, Eric reviewed Mastering Windows 8 C++ App Development, Packt Publishing.

Olivier Pons is a developer who's been bu i l d i ng websites si nce 1997. He is a teacher at
l n geS u p ( Ecole S u p e rie u re d ' l nge n ierie l nformatique http : / /www . i ngesup . com/ and
http : / /www . y - nov . com), at the U n ive rsity of Sciences (I UT) i n Aix-en-Provence, France.
At Ecole d ' l n ge n i e u rs d es M i nes d e Gardan ne, he teaches state-of-the-a rt web tec h n i q ues,
such as MVC fu ndamenta ls, Symfony, Word Press, P H P, HTM L, CSS, jQuery/jQuery Mobile,
Node.js, Angu l a rJS, Apache, Li n ux basics, a n d adva n ced Vi m tec h n i q ues. He has a l ready
worked as a tec h n ical reviewer for Ext JS 4 First Look, jQuery Hotshot, jQuery Mobile Web
Development Essentials, WordPress Complete, and jQuery 2.0 for Designers Beginner's
Guide Second Edition. All these books were publ ished by Packt Publishi ng. I n 2011, he
l eft h is fu l l-ti me job as a Del p h i and PH P d eveloper to concentrate on h is own compa ny,
H Q F Development (http : / /hqf . f r) . He cu rrently runs a n u m ber of websites i n c l u d i ng
http : / /www . bat t l e s oop . f r, http : / /www . krys t a l l opol i s . f r / (wh ich wi l l be
released soon), http : I /www . l i vrep i z z a s . f r, http : I /www . papdevi s . f r, and
http : / / o l ivi e rpons . f r (his own web d evelopment blog) . He a lso works as a consu lta nt,
teacher, and project m a nager, a n d so meti m es, helps big compan ies as a senior / h ighly
skil led d eveloper.
-

www.it-ebooks.info


Jorge H. Rodriguez has a backgro u n d i n softwa re development and more than 20 yea rs
of experience under his belt, m a ny of them working with Del p h i .

Always on t h e lookout for new and exciti ng technologies, Jorge l ives to code and spends m uch
of h is spare ti me rea d i ng techn ical books and playi ng o n l i n e chess. D u ring wi nters, he l i kes to
go snowboa rd i ng with his o n ly so n , Ca m i lo.
Jorge resides i n Va ncouver, Ca nada, awa iti ng his Colombian gi rlfriend, Shana. He can be
contacted at delphi . deve l ope r@shaw . ca.

www.it-ebooks.info


www.PacktPub.com

Support files, eBooks, discount offers, and more
You m ight wa nt to visit www . Packt Pub . com for support fi les and down loads related to
you r book.
Did you know that Packt offers e Book ve rsions of every book p u b l ished, with PDF and ePub
fi les ava i l a ble? You ca n u pgrade to the eBook version at www . Packt Pub . com and as a print
book customer, you a re entitled to a d isco u nt on the eBook copy. Get i n touch with us at
s e rv i ce®packtpub . com for more deta i ls.
At www . Packt Pub . com, you ca n a lso read a col l ection of free tec h n ical a rticles, sign up
for a ra nge of free newsletters and receive excl usive d iscou nts and offers on Packt books
and eBooks.

[dJ PACKTLi

http : / / Packt Lib . Packt Pub . com
Do yo u need i nsta nt so l utions to you r IT q u estions? Packtlib is Packt's o n l i n e d igita l book
l i bra ry. Here, you ca n access, read and sea rch across Packt's enti re l i bra ry of books.

Why subscribe?
"'

Fu l ly sea rchable across every book publ ished by Packt

"'

Copy a n d paste, pri nt and bookmark content

"'

On demand and accessible via web browser

Free access for Packt account holders
If you have an acco u nt with Packt at www . Packt Pub . com, you can use this to access
Packtl i b today and view n i n e enti rely free books. S i m ply use you r logi n cred enti a ls for
i m med iate access.

www.it-ebooks.info


www.it-ebooks.info


Table of Contents
�fu�

1

Chapter 1: Delphi Basics

7

Introduction

7

Changing your application's look and feel with VCL styles and no code

8

Changing the style of your VCL application at runtime

10

Customizing TDBGrid

14

Using the owner's draw combos and listboxes

20

Creating a stack of embedded forms

23

Manipulating JSON

26

Manipulating and transforming XML documents

32

1/0 in the twenty-first century - knowing streams

38

Putting your VCL application in the tray

42

Creating a Windows service

48

Associating a file extension with your application on Windows

53

Chapter 2: Become a Delphi Language Ninja

59

Introduction

59

Fun with anonymous methods - using higher-order functions

59

Writing enumerable types

64

RTII to the rescue - configuring your class at runtime

68

Duck typing using RTII

72

Creating helpers for your classes

76

Checking strings with regular expressions

84

Chapter 3: Going Cross Platform with FireMonkey

91
91

Introduction
Giving a new appearance to the standard FireMonkey
controls using styles

92

Creating a styled TListBox

98

www.it-ebooks.info


Table of Contents

-------

Impressing your clients with animations

102

Using master/details with LiveBindings

105

Showing complex vector shapes using paths

116

Using FireMonkey in a VCL application

122

Chapter 4: The Thousand Faces of Multithreading

129

Introduction

129

Synchronizing shared resources with TMonitor

129

Talking with the main thread using a thread-safe queue

137

Synchronizing multiple threads using TEvent

140

Displaying a measure on a 2D graph like an oscilloscope

143

Chapter 5: Putting Delphi on the Server

147

Introduction

147

Web client JavaScript application with WebBroker on the server

148

Converting a console service application to a Windows service

157

Serializing a dataset to JSON and back

160

Serializing objects to JSON and back using RTII

165

Sending a POST HTIP request encoding parameters

171

Implementing a RESTful interface using WebBroker

174

Controlling remote applications using UDP

190

Using App Tethering to create a companion app

197

Creating DataSnap Apache modules

203

Chapter 6: Riding the Mobile Revolution with FireMonkey

213

Introduction

213

Taking a photo, applying effects, and sharing it

214

Using listview to show and search local data

222

Do not block the main thread!

227

Using SQLite databases to handle a to-do list

234

Using a styled TListView to handle a long list of data

239

Taking a photo and location and sending it to a server continuously

247

Talking to the backend

257

Making a phone call from your app!

264

Tracking the application's life cycle

269

---[]]f-----�

www.it-ebooks.info


------

Chapter 7: Using Specific Platform Features

Table of Contents
275
27 5

Introduction
Using Android SOK Java classes

276

Using iOS Objective-C SOK classes

282

Displaying PDF files in your app

286

Sending Android intents

291

Letting your phone talk - using the Android TextToSpeech engine

300

305

Index

--------�O!D-

www.it-ebooks.info


www.it-ebooks.info


Preface
If you've been a softwa re developer for a long time, you certa i n ly know how usefu l a
conversation ca n be with a col l eague who a l ready d i d so m eth i ng s i m i l a r to what you a re
doi ng, and can d iscuss it as he/she may have faced the sa me proble m . It is not possible to
i n c l u d e a l l the possible situati ons that a developer may face i n a book, but most problems a re
si m i la r at least i n pri nciple. This is the reason this book is orga n ized as a cookbook; j ust l i ke
how a com bi nation of foods can be ada pted and mod ified to be appropriate for d iffe rent types
of meals. A progra m m i ng reci pe ca n provide the idea to solve m a ny d ifferent problems.
This book is a n adva nced-level gu ide that will help Del p h i developers become experts i n the i r
every day j o b . T h e every day job and t h e q u a l ity o f you r del iverables is what contri bute to the
q u a l ity of you r professional l ife. It does not m a ke sense to rei nvent the wheel repeated ly,
espec i a l ly when working with a well-esta bl ished tool such as Del p h i . The focus of this book is
to provide readers with com p rehensive a n d deta i led exa m ples on how effective ly the Del p h i
softwa re can b e d esigned and writte n . Al l t h e reci pes i n t h i s book a re a resu lt o f yea rs of
d evelopment, tra i n i ng, a n d consu lta ncy activities i n the most d ifferent fields of the IT i n d ustry,
from s m a l l systems with thousa nds of i nsta l l ations to la rge systems com m issioned by a ny big
com pa ny or govern ment. It is not a magic book that wi l l solve all you r development problems
(if you fi nd it, tel l m e please!), but it can be a va l i d sou rce of help to get a d ifferent point of
view on a specific problem, or a h i nt on how to solve problems.
Armed with the knowledge of advanced concepts, such as high-order fu nctions and
a nonym ous m ethods, generics and e n u merables, extended RTTI and d uck typ i ng,
Live B i n d i ngs, m u ltith rea d i ng, Fire M o n key, mobile developm ent, server-side d evelopment
and m a ny more, yo u w i l l be pleasantly su rprised as to how q u ickly and easily yo u ca n use
Del p h i to write h igh q u a l ity, clea n , readable, m a i nta i n a ble, and extensible code.
I have read too many boring progra m m i ng books, so I tried to m a i nta i n a relaxed a n d l ight
expositio n . A s m a l l appl icabi l ity scenario, which descri bes a situation where a parti c u l a r
technology, approach , or d esign pattern ca n b e used successfu l ly, i ntrod uces a l l t h e reci pes.
The reci pes a re not too complex beca use otherwise the book may consist of thousa nds of
pages; however, it is a lso not trivia l beca use the IT books landscape is a l ready fu l l of trivial
exa m p les with a few d i rect a p p l i cations. I tried to do a good trade-off and hope I succeed ed .

www.it-ebooks.info


Every time I sta rt to read a new book, I ask myself, "Wi l l the a uthor have someth ing i nteresti ng
to say?", " H ow m uch wi l l this book cha nge my poi nt of view on the topics it ta l ks about?",
or "Wi l l it be worth the time to read this book?". Now that I'm on the other side of the river, I
worked hard to put as m uch good q u a l ity content as possible i n this book, which I hope w i l l
match you r expectations.
On a fi nal note, writi ng h u n d reds of pages a bout adva nced progra m m i ng is not a n easy task.
However, I a m very pleased to have done it, and I hope yo u wi l l enjoy read i ng it as m u ch as I
enj oyed writi ng it.

What this book covers
Chapter 1, Delphi Basics, ta l ks about a set of genera l approaches that should not be ignored
by a ny Del p h i progra m mer. Some reci pes a re s i m ple, wh i l e some a re not, but a l l of them
should be deeply understood . By the end of this cha pter, yo u wi l l be a ble to use some of the
fu ndamenta l Del p h i tech n i q u es related to the RTL, VCL, and OS i ntegratio n .
Chapter 2 , Become a Delphi Language Ninja, focuses on t h e Obj ect Pasca l language. A
progra m m i ng language is the way yo u ta l k to the mach i ne, so you m ust be fl uent a n d should
know a l l the possibil ities offered . This chapter tal ks about h igher-order fu nctions, practical
uti l i zation of the extended RTII , regu lar expressions, and other th i ngs usefu l to a ugment the
power of you r code and lowe r the a m o u nt of time spent on debuggi ng.
Chapter 3, Going Cross Platform with FireMonkey, is ded icated to the Fire M o n key fra m ework
in genera l . What you wi l l learn from this chapter can be used in m a ny of the platforms
Fire M o n key su pports. Moreover, you w i l l learn about nontrivia l Live B i n d i ngs uti l i zations.
Chapter 4, The Thousand Faces of Multithreading, is one of the most com p l ex chapte rs. It
ta l ks a bout thread syn c h ro n i zation and the mechan isms used to obta i n this synchronization,
i n c l u d i ng TMon itor, thread-safe q u eues, a n d TEvent. By the end of this cha pter, yo u w i l l be
able to create a n d com m u n icate with backgro u n d th reads, leaving the m a i n th read free to
u pdate yo u r G U I (or com m u n icate with the OS) .
Chapter 5, Putting Delphi on the Server, focuses on how wel l Del p h i can behave when ru n n i ng
on a server. Some people th i n k that Del p h i is a client-on ly tool , but it is not true; the n u m ber
of Del p h i server-side systems ru n n i ng all over the world prove it! In this cha pter, we' l l show
how to create powerfu l servers that offer services over a netwo rk. Then, i n one of the reci pes,
we' l l a lso i m plement a JavaScript cl ient that bri ngs the database data to the user's browser.
The tec h n i q ues exp lai ned i n this chapter open a ra nge of possibi l ities, especia l ly in the mobile
and web a rea.

www.it-ebooks.info


Chapter 6, Riding the Mobile Revolution with FireMonkey, is dedicated to mobile development
with Del p h i and Fire M o n key. If you a re i nte rested in mobile developm ent, I th i n k that this wi l l
b e you r favorite chapter! Mobiles a re everywhere and this chapte r wi l l exp l a i n how to write
softwa re for you r And roid or iOS d evice, what a re the best practices to use, how to save you r
data on you r mobile device, how to retrieve a n d u pdate remote data, a n d how to i ntegrate with
a mobile operati ng system .
Chapter 7 , Using Specific Platform Features, shows you how to i ntegrate yo u r a p p with the
u n d erlyi ng mobile operati ng systems beyond what Fire M o n key offers. You wi l l learn how to
i m port Java a n d Objective-C l i bra ries i n you r app and use the S O K classes from you r Object
Pasca l cod e.

What you need for this book
This book ta l ks about Del p h i , so you need Del p h i . Not a l l reci pes a re ava i lable i n a l l the Del p h i
ed itions. Typical ly, t h e m o b i l e projects ca n b e com p i led o n ly i f you have Del p h i Enterp rise or
better (or Del p h i Professional p l us the mobile add-on, or RAD Stud i o professional, or better).
All the projects a re com p i led and tested on Del p h i XE6. Many of the reci pes can also be
com p i l ed on older versions.
If you wa nt to ru n the mobile app on a phone or ta blet, you can use the And roid e m u l ator or
iOS si m u l ator, but it is strongly reco m m ended that you use a n actu a l device to see how the
app rea l ly behaves. To deploy a n iOS app on you r device, yo u a lso need a n Apple com p uter
with Mac OS X. More i nformation is provided i n the related cha pters.

Who this book is for
This book a i ms to h e l p professional Del p h i developers i n their day-to-day jobs. This book wi l l
teach you a bout the newest Del p h i technologies and its hidden gems. I t i s not a book for a
newbie, but the practical approach wi l l help you reach a new leve l i n you r Del p h i ski l ls. An
experienced d eveloper wi l l benefit from th is book beca use nontrivial problems a re solved
using the best practices. Where more than one way is ava i lable or the topics are too vast to be
exp lai ned i n the ava i lable pages, references a re provided that a l low i nterested readers
to go deeper i n that field . It is a book that' l l hold on to you r desk for the next few yea rs.

Conventions
I n th is book, you wi l l fi nd a n u m ber of styles of text that d isti ngu ish between d ifferent kinds of
i nformatio n . Here a re some exa m ples of these styles, and an explanation of their mea n i ng.
Code words in text, database table names, folder names, fi lena mes, fi le extensions, path names,
d u m my U R Ls, user i n p ut, and Twitter handles are shown as follows: "The TStyl eManager .
S tyl eName s property conta i ns a l l na mes of the avai lable styles."

www.it-ebooks.info


A block of code is set as follows:

LogMe s sage ( ' Your me s sage goe s here for SUCCES S ' ,
EVENTLOG_SUCCES S , 0 , 1 ) ;
When we wish to d raw yo u r attention to a particular part of a code block, the releva nt l i nes or
items a re set i n bol d :

begin
App l i ca t i on . In i t i a l i z e ;
App l i ca t i on . MainFormOnTaskbar

: =

True ;

T S tyl eManager . TryS e t S tyl e ( ' Iceberg C l a s s i co ' ) ;

App l i ca t i on . Create Form ( TMainForm , Ma inForm) ;
App l i ca t i on . Run ;
end .
Any com mand-l i ne i n put or output is written as fol l ows:
C : \\Windows S e rvi c e . exe /ins t a l l
C : \\Windows S ervi c eOrGUI . exe /GUI

New terms and important words a re shown i n bol d . Words that you see on the screen , i n
m e n us or d ialog boxes for exa m ple, a p pear i n the text l i ke this: "Cl ick on Start, wa it for the
confi rmation, and the service should sta rt to write its logfi le."

[�
[ --R
'-'()

Warnings or important notes appear in a box like this.

Tips and tricks appear like this.

]
]

Reader feedback
Feed back from o u r readers is a lways welcome. Let us know what you th i n k about this
book-what you l i ked or may have d is l i ked . Reader feed back is i m porta nt for us to develop
titles that you rea l ly get the most out of.
To send us genera l feedback, s i m ply send an e-m a i l to feedback@packtpub . com,
a n d mention the book title via the subject of you r m essage.
If there is a topic that you have expertise i n and you a re i nterested i n either writi ng or
contri buti ng to a book, see o u r a uthor gu ide on www . packtpub . com/ authors.

www.it-ebooks.info


Customer support
Now that you a re the proud owner of a Packt book, we have a n u m ber of th i ngs to h e l p you
to get the most from yo u r p u rchase.

Downloading the example code
You ca n down load the exa m ple code fi les for a l l Packt books yo u have p u rchased from
you r acco u nt at http : / /www . packtpub . com. If you p u rchased this book elsewhere, you
can visit http : I /www . packtpub . com/ support and register to have the fi les e-ma i led
d i rectly to you .

Errata
Although we have taken every ca re to ensure the accu racy of o u r content, m ista kes do
happen . If you fi nd a m ista ke i n one of o u r books-maybe a m ista ke i n the text or the
cod e-we wo u l d be gratefu l if you wou l d report this to us. By doing so, you can save other
readers from frustration and help us i m p rove subseq uent versions of this book. If you fi nd
a ny errata, please report them by visiti ng http : I /www . packtpub . com/ submi t - e rrata,
selecti ng you r book, clicking on the errata submission form l i n k, a n d entering the deta i ls
of you r errata . Once you r errata a re ve rified, you r subm ission wi l l be accepted a n d the errata
w i l l be u p l oaded on o u r website, or added to a ny list of existing errata, under the Errata
section of that title. Any existi ng errata can be viewed by selecti ng you r title from

http : / /www . packtpub . com/ support.

Piracy
Pi racy of copyright material on the I nternet is an ongoing problem across a l l m ed i a . At Packt,
we ta ke the protection of o u r copyright a n d l i censes very seriously. If you come across a ny
i l l egal copies of o u r works, i n a ny form, on the I nte rnet, please provide us with the location
add ress or website name i m med iately so that we can p u rsue a remedy.
Please contact us at copyr ight@packtpub . com with a l i n k to the suspected
pi rated materia l .
We appreciate you r h e l p i n protecting o u r a uthors, and our abil ity to bring you va l uable content.

Questions
You ca n contact us at que s t i ons@packtpub . com if you are having a problem with a ny
aspect of the book, and we wi l l do o u r best to add ress it.

www.it-ebooks.info


www.it-ebooks.info


1

Delphi Basics
I n th is cha pter, we wi l l cover the fol lowi ng reci pes:
.,.

Changi n g you r a p p l i cation's look and feel with VCL styles and no code

.,.

Changi n g the style of you r VCL appl ication at ru nti m e

.,.

Custom izing TDBGrid

.,.

Using the owner's d raw com bos and l istboxes

.,.

Creating a stack of em bedded forms

.,.

M a n i p u lati ng JSON

.,.

M a n i p u lati ng a n d tra nsform ing XM L docu ments

.,.

1/0 i n the twenty-first centu ry - knowing streams

.,.

Putti ng you r VCL appl ication i n the tray

.,.

Creating a Windows service

.,.

Associati ng a fi le extension with you r a p p l ication on Windows

I ntrod uct i o n
This chapte r expl a i ns some of the day-to-day needs of a Del p h i progra m mer. These a re
ready-to-use reci pes that w i l l be usefu l every day and have been selected a head of a lot of
others beca use a lthough they may be obvious for some expe rienced users, they a re sti l l very
usefu l . Even if there is no specifica l ly data base-related code, m a ny of the reci pes can a lso be
used (or someti m es especially used) when you a re dea l i ng with data .

www.it-ebooks.info


Delphi Basics

----

Chang i ng you r a p p l i cati o n 's l ook and feel
with VC L styl es and no code
VCL styles a re a major new entry i n t h e latest versions o f Del p h i . They have been i ntrod uced
in Del p h i XE2 and are sti l l one of the less-known featu res for the good old Del p h i developers.
However, as usua l , some busi nessmen say looks matter, so the look and feel of you r
appl ication cou l d b e o n e of t h e reasons to choose you r prod uct over o n e from a com petitor.
Consider that with a few mouse clicks you can apply m a ny d iffe rent styles to you r appl ication
to cha nge the look and feel of you r a p p l i cations. So why not give it a try?

Getting ready
VCL styles ca n be used to reva m p a n old appl ication or to create a new one with a
nonsta n d a rd G U I . VCL styles are a com p l etely d ifferent beast to Fire M o n key styles.
They a re both styles but with completely d ifferent approaches and behavior.
To get started with VCL styles, we' l l use a new appl icati o n . Let's create a new VCL a p p l ication
and d rag-a nd-d rop som e components onto the m a i n form (for exa m ple, two TButton
components, one TListBox component, one TCom boBox component, and a couple of
TCheckBox components) .
T h e fo l l owing screenshot is t h e resu lta nt form that r u n s on a Windows 7 machine:

I

I'm• sad not
Button!

]I

styled form ...
Button I

J

Label 1
ComboBoxl

D Check!loxl

D Check!loxl

A form without style

How to do it...
Now we've to apply a set of n ice styles. To do this, perform the fol lowing ste ps:
1.

Navigate to Project I Options. In the resu lta nt d i a log, go to Application I
Appearance and select a l l the styles that we wa nt to i n c l u d e in o u r a p p l icati o n .

www.it-ebooks.info


2.

Using the Preview button, the I D E shows a s i m p l e d e m o fo r m with some controls, a n d
we c a n get a n idea about the fi nal resu lt o f o u r styled form . Feel free to experiment
and choose the style-or set of styles-that you l i ke. O n ly one style wi l l be used at a
ti me, but we can l i n k the necessa ry resou rces to the executa ble and select the proper
one at ru nti me.

3.

After selecti ng a l l the req u i red styles from the l ist, we've to select one i n the
com bobox at the bottom of the screen . This style wi l l be the d efa u lt style for our form
and wi l l be loaded as soon as the a p p l ication sta rts. You can delay this choice and
m a ke it at ru nti me usi ng code if you prefer.

4.

Click on OK and h it F9 (or navigate to Run I Run) and you r appl ication is styl ed ! The
resu ltant form is shown i n the fol lowi ng screenshot:

Labell

(comb oBox 1

...,.

I

Check8ox1
CheckBox1

The sa me form as the preced i n g one but with the Iceberg Classico style a p p l ied

How it works...
Sel ecti ng one or more styles by navigati ng to Project I Options I Application I Appearance
can ca use the Del p h i l i n ker to l i n k the style resou rce to you r executa ble. It is possible to l i n k
m a ny styles to yo u r executa ble, but you c a n use o n ly o n e style a t ti me. So, how does Del p h i
know w h i c h style you want t o use w h e n there are more t h a n one styles? I f w e check the
Proj e c t fi le (the fi le with the . dpr extension) by navigating to Project I View Sou rce,
you can see where and how this l ittle magic ha ppens.
The fo l l owing l i nes a re the i nteresting part:

begin
App l i ca t i on . In i t i a l i z e ;
App l i ca t i on . MainFormOnTaskbar

: =

True ;

T S tyl eManager . TryS e t S tyl e ( ' Iceberg C l a s s i co ' ) ;

App l i ca t i on . Create Form ( TMainForm , Ma inForm) ;
App l i ca t i on . Run ;
end .

www.it-ebooks.info


Delphi Basics

----

When we've selected the Iceberg Classico style as the defa u lt style, the Del p h i I D E adds
a line j ust before the creation of the main form , setting the defa u lt style for the appl ication
using the T S tyl eManage r . TryS e t S tyle static method .

T S tyl eManager is a very i m porta nt class when dea l i ng with VCL styles. We' l l see more about
it i n the next rec i pe when we'l l learn how to cha nge a style at ru nti me.

There's more...
Del p h i and C++ Bui lder XE6 com e with 29 VCL styles ava i lable in c : \ Program F i l e s
( x8 6 ) \ Embarcadero \ S tudio\ 1 4 . O \Redi s t \ s tyl e s \vcl \ (with a sta ndard i nsta l lation).
M oreover, it is possible to create you r own styles or mod ify the existing ones by usi ng the
Bitmap Style Designer avai lable at Tools I Bitmap Style Designer m en u . The Bitma p Style
Designer a lso provides test a p p l i cations to test VCL styles.
For more deta i ls on how to create or custom ize a VCL styl e, check the fol lowing l i n k:

http : / / docwi ki . embarcade ro . com/RADS tudio/XE 6 / en/Creat i ng_a_S tyle_
u s ing_the_B i tmap_S tyle_Des igne r

Chang i ng the style of you r VC L a p p l i cati o n
a t ru n t i m e
VCL styles a re a powerfu l way to cha nge the a p pea ra nce of you r appl icatio n , but using them
o n ly as design-ti me tools is way too l i m ited . One of the m a i n featu res of a VCL style is the
a b i l ity to cha nge the style w h i l e a n appl ication is ru n n i ng.

Downloading the example code
You can download the example code files for all Packt books you have
purchased from your account at

http : I /www . packtpub . com. If you
http : I /www . packtpub .

purchased this book elsewhere, you can visit

com/ support

and register to have the files e-mailed directly to you.

Getting ready
Beca use a VCL style is s i m ply a particu l a r kind of binary fi le, we can a l l ow o u r users to load
the i r preferred style at ru nti me, and we can even provide new styles-pu blish i ng them on a
website or sen d i n g them by an e-ma i l to o u r customers.
In th is rec i pe, we' l l be able to cha nge the style w h i l e a n a p p l ication is ru n n i ng using a style
a l ready l i n ked at design time or let the user choose between a set of styles deployed i nside
a folder.

www.it-ebooks.info


How to do it...
Styles m a n i p u lation at ru nti me is done using the class methods of the TStyl eManager class:
1.

Create a brand new VCL appl ication and add the Vc l . Theme s and Vc l . S tyl e s
u n its to the m a i n i m plementation form . These u n its a re req u i red to use VCL styles
at ru nti me.

2.

Drop on the form a TListBox component, two TButton com ponents, and two
TOpenDialog components. Leave the defa u lt component names.

3.

Go to Project I Appearance a n d select eight styles of you r choice from the l ist. Leave
the Default style option to Windows.

4.

The T S tyl eManage r . Styl eName s property conta i ns all names of the ava i l a ble
styles. In the FormCreate event h a n d ler, we have to load the a l ready l i n ked styles
present in the executa ble to the l istbox to let the user choose one of them . So, create
a new proced u re cal led S tyl e sL i s tRe f re s h with the fol lowi ng code and ca l l it
from the FormCreate event hand ler:
proc edure

TMa inForm . S tyl e s L i stRe f resh ;

var

styl ename : s t ring ;
begin

L i s tBoxl . Clear ;
II retrieve all the styles linked in the executable
for styl ename in T S tyl eManager . S tyl eName s do
begin

L i s tBoxl . I t ems . Add ( styl ename ) ;
end ;
end ;

5.

I n t h e B u t tonl C l i ck event hand ler, we've t o set t h e cu rrent style accord i ng to the
one selected from L i s tBoxl using the fol lowing cod e:

TStyl eManager . S etStyle ( L i s tBoxl . I t ems [ L i s tBoxl . I t emindex] ) ;
6.

The But ton2 C l i ck event handler should a l low the user to sel ect a style from
d isk. So, we have to create a folder named s tyl e s at level of o u r executa ble and
copy a few . vs f fi les from the defa u lt style d i rectory which is c : \ Program F i l e s
( x8 6 ) \ Embarcadero \ S tudi o \ 1 4 . O \Redi s t \ s tyl e s \vcl \ i n RAD Stud i o XE6.

7.

After copyi ng the fi les, write the fol lowi ng code u n d e r the But ton2 C l i ck event
h a n d ler. This code a l l ows the user to chose a style fi le d i rectly from the d isk. Then you
can select one of the loaded styles from the l istbox a n d click on Button1 to a p ply it to
the appl icati o n . The code is as follows:
if

OpenD i a l og l . Execute

then

begin
if

TStyl eManage r . I sVa l i dStyl e ( OpenD i a l og l . F i l eName )

www.it-ebooks.info

then


Tài liệu bạn tìm kiếm đã sẵn sàng tải về

Tải bản đầy đủ ngay

×