00 9721 CD-FM
4.6.01
1:58 PM
Page i
C++Builder™ 5 Developer’s Guide Jarrod Hollingworth Dan Butterfield Bob Swart Jamie Allsop
201 West 103rd St., Indianapolis, Indiana, 46290 USA
00 9721 CD-FM
4.6.01
1:58 PM
Page ii
C++Builder™ 5 Developer’s Guide
ASSOCIATE PUBLISHER
Copyright
ACQUISITIONS EDITOR
©
2001 by Sams Publishing
All rights reserved. No part of this book shall be reproduced, stored in a retrieval system, or transmitted by any means, electronic, mechanical, photocopying, recording, or otherwise, without written permission from the publisher. No patent liability is assumed with respect to the use of the information contained herein. Although every precaution has been taken in the preparation of this book, the publisher and author assume no responsibility for errors or omissions. Nor is any liability assumed for damages resulting from the use of the information contained herein. International Standard Book Number: 0-672-31972-1 Library of Congress Catalog Card Number: 00-102818 Printed in the United States of America First Printing: November 2000 03
02
01
00
Michael Stephens
Carol Ackerman
DEVELOPMENT EDITOR Robyn Thomas
MANAGING EDITOR Matt Purcell
PROJECT EDITOR Andrew Beaster
INDEXERS Sandy Henselmeier Eric Schroeder
PROOFREADERS 4
3
2
1
Candice Hightower Jessica McCarty
Trademarks
TECHNICAL EDITORS
All terms mentioned in this book that are known to be trademarks or service marks have been appropriately capitalized. Sams Publishing cannot attest to the accuracy of this information. Use of a term in this book should not be regarded as affecting the validity of any trademark or service mark.
Peter Nunn Paul Strickland John Thomas Eamonn Wallace
Warning and Disclaimer
TEAM COORDINATOR
Every effort has been made to make this book as complete and as accurate as possible, but no warranty or fitness is implied. The information provided is on an “as is” basis. The authors and the publisher shall have neither liability nor responsibility to any person or entity with respect to any loss or damages arising from the information contained in this book or from the use of the CD or programs accompanying it.
Pamalee Nelson
MEDIA DEVELOPERS William Eland Matt Bates
INTERIOR DESIGNER Anne Jones
COVER DESIGNER Anne Jones
LAYOUT TECHNICIANS Ayanna Lacey Heather Hiatt Miller Stacey Richwine-DeRome
00 9721 CD-FM
4.6.01
1:58 PM
Page iii
Overview Introduction
1
PART I
C++Builder 5 Essentials
1
Introduction to C++Builder
2
C++Builder Projects and More on the IDE
3
Programming in C++Builder
4
Advanced Programming with C++Builder
5
User Interface Principles and Techniques
6
Compiling and Optimizing Your Application
7
Debugging Your Application
8
Using VCL Components
9
Creating Custom Components
9
95
335
389
437 499
Creating Property and Component Editors
11
More Custom Component Techniques
577
701
Communications, Database, and Web Programming
12
Communications Programming
13
Web Server Programming
14
Database Programming
PART III
147 225
10
PART II
53
775
813
861
Interfaces and Distributed Computing
15
DLLs and Plug-Ins
925
16
COM Programming
17
Going Distributed: DCOM
18
One Step Ahead: COM+
19
Multi-Tier Distributed Applications with MIDAS 3
20
Distributed Applications with CORBA
21
Microsoft Office Integration 1195
22
Using ActiveX Techniques
967 1023 1057
1233
1173
1121
00 9721 CD-FM
4.6.01
1:58 PM
PART IV
Page iv
Advanced Topics
23
Data Presentation with C++Builder
24
Using the Win32 API
25
Multimedia Techniques
26
Advanced Graphics with DirectX and OpenGL
PART V
1279
1351 1457
C++Builder Application Deployment
27
Creating Help Files and Documentation
28
Software Distribution 1593
29
Software Installation and Updates
PART VI
Knowledge Base
30
Tips, Tricks, and How Tos 1675
31
Real-World Examples 1809
PART VII A
Appendix Information Sources 1825
1625
1561
1505
00 9721 CD-FM
4.6.01
1:58 PM
Page v
CONTENTS
Contents Introduction
Part I 1
1
C++Builder 5 Essentials Introduction to C++Builder 9 C++Builder Basics ................................................................................10 Hello World! A Basic Start ..............................................................10 The VCL, Forms, and Components..................................................12 The Component Palette ....................................................................14 Your First Real Program ..................................................................17 How to Get Around ..........................................................................23 What’s New in C++Builder 5 ................................................................24 Web Programming............................................................................25 Distributed Applications ..................................................................26 Team Development ..........................................................................26 Application Localization ..................................................................26 Debugging ........................................................................................27 Database Application Development ................................................27 Developer Productivity ....................................................................27 Companion Tools CD-ROM ............................................................28 Upgrading and Compatibility Issues ....................................................28 Upgrading C++Builder from an Earlier Version ..............................28 Using Existing Projects in C++Builder 5 ........................................29 Creating Projects Compatible with Previous Versions of C++Builder ....................................................................................29 Solving Other Project Upgrading Issues ..........................................30 Migration from Delphi ..........................................................................30 Comments ........................................................................................31 Variables ..........................................................................................31 Constants ..........................................................................................32 Operators ..........................................................................................33 Controlling Program Flow................................................................36 Functions and Procedures ................................................................38 Classes ..............................................................................................40 Preprocessor Directives ....................................................................42 Types of Files ..................................................................................43 Advantages and Disadvantages of C++Builder 5..................................44 Visual Reality: True Rapid Application Development ....................44 Keeping Up with the Joneses: The C++ Standard ..........................46 Choosing the Right Development Environment ..............................47 C++Builder Advantages and Disadvantages Conclusion ................47
v
00 9721 CD-FM
vi
4.6.01
1:58 PM
Page vi
C++BUILDER 5 DEVELOPER’S GUIDE Preparation for Kylix ............................................................................48 Similarities Between Kylix and C++Builder ..................................48 Differences Between Kylix and C++Builder ..................................49 Porting C++Builder Projects to Kylix..............................................50 So When?..........................................................................................50 Summary ................................................................................................51 2
C++Builder Projects and More on the IDE 53 Understanding C++Builder Projects......................................................54 Files Used in C++Builder Projects ..................................................54 Project Manager................................................................................57 Using the Object Repository..................................................................58 Adding Items to the Object Repository............................................58 Using Items in the Object Repository ..............................................63 Sharing Items Within a Project ........................................................63 Customizing the Object Repository ................................................64 Creating and Adding a Wizard to the Object Repository ................64 Understanding and Using Packages ......................................................67 Considerations when Using Packages..............................................70 The C++Builder Runtime Packages ................................................72 Using Tdump ....................................................................................75 Introducing New IDE Features in C++Builder 5 ..................................76 Property Categories in the Object Inspector ....................................76 Images in Drop-Down Lists in the Object Inspector ......................78 The XML Project File Format..........................................................80 Forms—Save as Text ........................................................................82 The Node-Level Options ..................................................................83 The New To-Do List ........................................................................87 The Console Wizard ........................................................................90 Summary ................................................................................................93
3
Programming in C++Builder 95 Coding Style to Improve Readability ....................................................96 The Use of Short and Simple Code ................................................97 The Use of Code Layout ................................................................98 The Use of Sensible Naming ........................................................104 The Use of Code Constructs ........................................................111 The Use of Comments ..................................................................112 A Final Note on Improving the Readability of Code ....................117 Better Programming Practices in C++Builder ....................................117 Use a String Class Instead of char* ..............................................117 Understand References and Use Them Where Appropriate ..........118 Avoid Using Global Variables ........................................................121
00 9721 CD-FM
4.6.01
1:58 PM
Page vii
CONTENTS Understand and Use const in Your Code ......................................127 Be Familiar with the Principles of Exceptions ..............................129 Use new and delete to Manage Memory ......................................134 Understand and Use C++-Style Casts ............................................138 Know When to Use the Preprocessor ............................................141 Learn About and Use the C++ Standard Library ..........................143 Further Reading ..................................................................................144 Summary ..............................................................................................146 4
Advanced Programming with C++Builder 147 Introducing the Standard C++ Library and Templates........................148 Understanding C++ Templates ......................................................148 Exploring the Standard C++ Library Features ..............................152 Coming to Grips with Containers and Iterators ............................153 Using the Standard Algorithms ......................................................161 Closing Thoughts on the SCL ........................................................162 Using Smart Pointers and Strong Containers ......................................163 The Heap Versus the Stack ............................................................163 Pointers ..........................................................................................163 A Strong Container ........................................................................168 Pitfalls ............................................................................................170 Smart Pointers and Strong Containers Summary ..........................170 Implementing an Advanced Exception Handler..................................171 Reviewing the Strategy ..................................................................171 Reviewing the Advantages ............................................................172 Replacing the Compiler’s Default Exception Handler ..................172 Adding Project-Specific Information to the Class ........................174 The Exception Handler’s Source Code ..........................................174 Advanced Exception Handler Summary ........................................193 Creating Multithreaded Applications ..................................................193 Understanding Multitasking ..........................................................194 Understanding Multithreading........................................................194 Creating a Thread Using API Calls................................................195 Understanding the TThread Object ................................................199 Understanding the Main VCL Thread............................................205 Establishing Priorities ....................................................................208 Timing Threads ..............................................................................211 Synchronizing Threads ..................................................................213 Introducing Design Patterns ................................................................218 Understanding the Recurring Nature of Patterns ..........................218 Recurring Patterns in Software Design ..........................................218 Design Patterns as a Vocabulary ....................................................219 Design Pattern Format....................................................................219
vii
00 9721 CD-FM
viii
4.6.01
1:58 PM
Page viii
C++BUILDER 5 DEVELOPER’S GUIDE Design Pattern Classification ........................................................220 Parting Thoughts About Design Patterns ......................................222 Summary ..............................................................................................222 5
User Interface Principles and Techniques 225 User Interface Guidelines ....................................................................226 The Example Projects Used in This Chapter ......................................229 Introducing the MiniCalculator Project..........................................230 Enhancing Usability by Providing Feedback to the User ..................231 Using TProgressBar and TCGauge ..................................................232 Using the Cursor ............................................................................233 Using TStatusBar ..........................................................................234 Using Hints ....................................................................................243 Enhancing Usability Through Input Focus Control ............................264 Responding to Input ......................................................................264 Moving Input Focus ......................................................................270 Enhancing Usability Through Appearance..........................................272 Using Symbols on Their Own with Buttons ..................................274 Using Symbols in Addition to Text ................................................275 Using Color to Provide Visual Clues ............................................280 Using Shaped Controls ..................................................................280 Enhancing Usability by Allowing Customization of the User Interface ....................................................................................283 Docking ..........................................................................................284 Resizing ..........................................................................................289 Using TControlBar ........................................................................299 Controlling Visibility ......................................................................313 Customizing the Client Area of an MDI Parent Form ..................317 Enhancing Usability by Remembering the User’s Preferences ..........317 Coping with Differing Screen Conditions ..........................................328 Coping with Different Screen Resolutions ....................................328 Coping with Different Font Sizes ..................................................328 Coping with Different Color Depths..............................................328 Coping with Complexity in the Implementation of the User Interface ....................................................................................329 Using Action Lists ..........................................................................329 Sharing Event Handlers..................................................................331 Summary ..............................................................................................334
6
Compiling and Optimizing Your Application 335 Understanding How the Compiler Works............................................336 Speeding Up Compile Times ..............................................................338 Precompiled Headers......................................................................338 Other Techniques for Speeding Up Compile Times ......................340
00 9721 CD-FM
4.6.01
1:58 PM
Page ix
CONTENTS Exploring the C++Builder 5 Compiler and Linker Enhancements ....341 Background Compilation................................................................342 Miscellaneous Compiler Enhancements ........................................343 New Linker Enhancements ............................................................343 Optimizing: An Introduction................................................................344 Optimizing for Execution Speed ........................................................346 Crozzle Solver Application Example ............................................347 Exponential Timings ......................................................................349 Project Options for Execution Speed ............................................351 Detecting Bottlenecks ....................................................................352 Optimizing the Design and Algorithms..........................................358 Exploring Techniques for Streamlining Code ................................365 Techniques for Streamlining Data..................................................379 Hand-Tuning Assembly Code ........................................................381 Using External Optimization..........................................................384 Execution Speed Optimization Summary ......................................385 Optimizing Other Aspects of Your Application ..................................385 Optimizing Program Size ..............................................................385 Final Optimization Aspects ............................................................386 Summary ..............................................................................................387 7
Debugging Your Application 389 Debugging Overview ..........................................................................390 Project Guidelines ..........................................................................391 Programming Guidelines................................................................392 The Debugging Task ......................................................................393 Basic Debugging Techniques ..............................................................394 Outputting Debug Information ......................................................395 Using Assertions ............................................................................400 Implementing a Global Exception Handler....................................402 Other Basic Debugging Issues ......................................................403 Using the C++Builder Interactive Debugger ......................................404 Advanced Breakpoints....................................................................405 New Breakpoint Features in C++Builder 5....................................409 C++Builder Debugging Views ......................................................409 Watches, Evaluating, and Modifying ............................................415 The Debug Inspector ......................................................................416 CodeGuard ..........................................................................................417 Enabling and Configuring CodeGuard ..........................................418 Using CodeGuard ..........................................................................419 Examining CodeGuard Errors and Their Causes ..........................421
ix
00 9721 CD-FM
x
4.6.01
1:58 PM
Page x
C++BUILDER 5 DEVELOPER’S GUIDE Advanced Debugging ..........................................................................426 Locating the Source of Access Violations......................................426 Attaching to a Running Process ....................................................428 Using Just-In-Time Debugging ......................................................428 Remote Debugging ........................................................................429 Debugging DLLs ............................................................................431 Looking at Other Debugging Tools................................................431 Testing..................................................................................................433 Testing Stages and Techniques ......................................................433 Testing Tips ....................................................................................435 Summary ..............................................................................................436 8
Using VCL Components 437 VCL Overview ....................................................................................438 It All Starts at TObject ..................................................................439 Building on Existing Objects ........................................................440 Using the VCL................................................................................442 The C++ Extensions ......................................................................445 The Streaming Mechanism ..................................................................452 Advanced Streaming Requirements ..............................................453 Streaming Unpublished Properties ................................................454 Common Control Updates ..................................................................458 Common Control Dynamic Link Library ......................................459 C++Builder Common Control Updates ........................................461 Miscellaneous VCL Enhancements ....................................................464 New Help Hint and Menu Features................................................464 Registry Access ..............................................................................465 VCL Documentation Enhancements ..............................................465 New TApplicationEvents Component ..........................................466 TIcon Enhancements ......................................................................466 Other Miscellaneous VCL Enhancements......................................466 Extending the VCL—More than Just a TStringList ..........................466 Using TStringList as a Container ................................................467 Storing Non-VCL Objects..............................................................467 Linking Strings to Objects of the Same Type ................................469 Creating a Chain of Events ............................................................479 Sorting the Lists..............................................................................480 Making Improvements....................................................................481 Advanced Custom Draw Events ..........................................................482 The TTreeView Component ............................................................483 The TListView Component ............................................................483 The TToolBar Component ..............................................................484 Advanced Custom Draw Events Example ....................................484
00 9721 CD-FM
4.6.01
1:58 PM
Page xi
CONTENTS Control Panel Applet Wizard Components..........................................484 The Basics of an Applet ................................................................484 Making Use of Third-Party Components ............................................495 Third-Party Component Advantages and Disadvantages ..............495 Where to Look for More C++Builder Resources ..........................496 Summary ..............................................................................................497 9
Creating Custom Components 499 Why Create Custom Components ......................................................500 Understanding Component Writing ....................................................501 Why Build Upon an Existing Component?....................................501 Designing Custom Components ....................................................503 Using the VCL Chart......................................................................504 Writing Non-Visual Components ........................................................504 Properties ........................................................................................504 Events ............................................................................................514 Methods ..........................................................................................517 Creating Component Exceptions....................................................519 The namespace ................................................................................521 Responding to Messages ................................................................522 Designtime Versus Runtime ..........................................................524 Linking Components ......................................................................526 Linking Events Between Components ..........................................529 Writing Visual Components ................................................................532 Where to Begin ..............................................................................532 TCanvas ..........................................................................................532 Using Graphics in Components ....................................................534 Responding to Mouse Messages ....................................................538 Putting It All Together ....................................................................539 Modifying Windowed Components ..............................................547 Creating Custom Data-Aware Components ........................................561 Making the Control Read-Only......................................................561 Establishing the Link......................................................................562 Using the OnDataChange Event ......................................................565 Changing to a Data-Editing Control ..............................................567 Working Toward a Dataset Update ................................................568 Adding a Final Message ................................................................571 Registering Components......................................................................571 Summary ..............................................................................................574
10
Creating Property and Component Editors 577 Creating Custom Property Editors ......................................................580 The GetAttributes() Method ......................................................593 The GetValue() Method ................................................................593
xi
00 9721 CD-FM
xii
4.6.01
1:58 PM
Page xii
C++BUILDER 5 DEVELOPER’S GUIDE The SetValue() Method ................................................................594 The Edit() Method ........................................................................595 The GetValues() Method ..............................................................600 Using the TPropertyEditor Properties ..........................................600 Considerations when Choosing a Suitable Property Editor ..........601 Properties and Exceptions....................................................................602 Registering Custom Property Editors ..................................................604 Obtaining a TTypeInfo* (PTypeInfo) from an Existing Property and Class for a Non-VCL Type ....................................606 Obtaining a TTypeInfo* (PTypeInfo) for a Non-VCL Type by Manual Creation ............................................................614 How to Obtain a TTypeInfo* for a Non-VCL Type ......................615 Rules for Overriding Property Editors ..........................................616 Using Images in Property Editors........................................................617 The ListMeasureWidth() Method..................................................622 The ListMeasureHeight() Method................................................623 The ListDrawValue() Method ......................................................624 The PropDrawValue() Method ......................................................629 The PropDrawName() Method ........................................................630 Installing Editor-Only Packages ..........................................................632 Using Linked Image Lists in Property Editors....................................634 The GetAttributes() Method ......................................................640 The GetComponentImageList() Method ........................................640 The GetValues() Method ..............................................................641 The ListMeasureWidth() and ListMeasureHeight() Methods ......641 The ListDrawValue() Method ......................................................643 The PropDrawValue() Method ......................................................645 Other Considerations when Rendering Images..............................647 Linking to a Parent’s TCustomImageList ......................................647 A Generalized Solution for ImageIndex Properties ......................652 Creating Custom Component Editors..................................................658 The Edit() Method ........................................................................664 The EditProperty() Method ........................................................668 The GetVerbCount() Method ........................................................670 The GetVerb() Method ..................................................................670 The PrepareItem() Method ..........................................................670 The ExecuteVerb() Method ..........................................................677 The Copy() Method ........................................................................678 Registering Component Editors ..........................................................680 Using Predefined Images in Custom Property and Component Editors............................................................................680 Adding Resource Files to Packages ..............................................682 Using Resources in Property and Component Editors ..................682
00 9721 CD-FM
4.6.01
1:58 PM
Page xiii
CONTENTS Registering Property Categories in Custom Components ..................687 Understanding Categories and Category Creation ........................688 Registering a Property or Properties in a Category........................690 Summary ..............................................................................................698 11
Part II 12
More Custom Component Techniques 701 Miscellaneous Considerations for Custom Components ....................702 Displaying a Class Property’s Published Properties in the Object Inspector ....................................................................702 Using Namespaces in Event Parameter Lists ................................703 Considerations when Determining an Event’s Parameter List ......704 Overriding DYNAMIC Functions........................................................709 Handling Messages in Custom Components..................................711 Using Windows Callback Functions in Components ....................726 Considerations when Choosing Fundamental Property Types ......736 Allowing for Designtime and Runtime Component Use ..............742 Frames..................................................................................................744 What Exactly Is a Frame? ..............................................................744 The TCustomFrame Class ................................................................744 Working with Frames at Designtime..............................................746 Working with Frames at Runtime ..................................................747 Creating a TFrame Descendant Class..............................................747 Inheriting from a TFrame Descendant Class ..................................751 Reusing Frames ..............................................................................752 Closing Remarks on Frames ..........................................................754 Component Distribution and Related Issues ......................................754 Packaging Components ..................................................................754 Where Distributed Files Should Be Placed....................................760 Naming Packages and Package Units ............................................762 Naming Components ......................................................................764 Distributing only a Designtime-Only Package ..............................764 Distributing Components for Different Versions of C++Builder ..................................................................................767 Creating Component Palette Bitmaps ............................................770 Using Guidelines in the Design of Components for Distribution ..................................................................................771 Taking a Look at Other Distribution Issues ..................................772 Summary ..............................................................................................772
Communications, Database, and Web Programming Communications Programming 775 Serial Communication ........................................................................776 Protocol ..........................................................................................777
xiii
00 9721 CD-FM
xiv
4.6.01
1:58 PM
Page xiv
C++BUILDER 5 DEVELOPER’S GUIDE State Machines................................................................................780 Architecture ....................................................................................781 Thread Synchronization Techniques ..............................................782 Buffering ........................................................................................782 Concluding Remarks on Serial Communications ..........................783 Internet Protocols—SMTP, FTP, HTTP, POP3 ..................................784 Tour of Component Tabs ................................................................784 An Example Chat Server................................................................785 An Example Chat Client ................................................................790 An Example Email Application......................................................793 An Example HTTP Server ............................................................802 Example FTP Client Software........................................................805 Summary ..............................................................................................811 13
Web Server Programming 813 Web Modules ......................................................................................814 Web Server Application Wizard ..........................................................814 CGI ................................................................................................815 WinCGI ..........................................................................................815 ISAPI/NSAPI..................................................................................815 CGI or ISAPI? ................................................................................815 WebBroker Support Components ........................................................816 TWebDispatcher ..............................................................................817 TWebModule ....................................................................................817 TWebResponse ..................................................................................819 TWebRequest....................................................................................820 Web Servers ........................................................................................820 WebBroker Producing Components ....................................................824 TPageProducer ................................................................................824 TDataSetPageProducer ..................................................................828 TDataSetTableProducer ................................................................831 TQueryTableProducer ....................................................................833 Web Application Wizards ....................................................................837 Maintaining State ................................................................................838 Fat URLs ........................................................................................838 Cookies ..........................................................................................839 Hidden Fields..................................................................................839 Web Security........................................................................................842 Secure Sockets Layer ....................................................................843 Authorization ..................................................................................843 Securing a Web Application ..........................................................845 HTML and XML ................................................................................851 XML ..............................................................................................851
00 9721 CD-FM
4.6.01
1:58 PM
Page xv
CONTENTS InternetExpress ....................................................................................853 Customer Orders ............................................................................853 TMidasPageProducer ......................................................................853 Deployment ....................................................................................855 Final Master-Detail ........................................................................856 Web Page Design Issues ................................................................858 Summary ..............................................................................................860 14
Database Programming 861 Architecture Models for Database Applications..................................862 The Borland Database Engine........................................................862 BDE Native (Single-Tier) ..............................................................863 BDE/SQL Links (Client/Server) ....................................................864 Distributed (Multitier) ....................................................................864 Data Access Methods ....................................................................865 Native Components ........................................................................866 ODBC Using the BDE ..................................................................866 ODBC Using Native Components ................................................867 ADO (ActiveX) ..............................................................................868 Embedded SQL ..............................................................................868 Native API ......................................................................................869 Database Architectures—Conclusion ............................................869 Sources for More Information on Database Architectures ............870 Structured Query Language (SQL)......................................................871 Tables and Indices ..........................................................................871 Parameters ......................................................................................872 insert, update, delete, and select ..............................................873 Aggregate Functions ......................................................................875 More Information on SQL..............................................................875 ADO Express Components for C++Builder........................................875 ADO Versus BDE ..........................................................................876 Component Overview ....................................................................877 Database Connections ....................................................................878 Accessing Datasets ........................................................................880 Accessing a Dataset with TADOTable..............................................880 Using TADOCommand for Dataset Access..........................................884 Managing Transactions ..................................................................884 Using Component Events ..............................................................884 Creating Generic Database Applications........................................886 Performance Optimizations ............................................................887 Error Handling Issues ....................................................................888 Multitier Applications and ADO ....................................................889 ADO Express Components—Conclusion ......................................889
xv
00 9721 CD-FM
xvi
4.6.01
1:58 PM
Page xvi
C++BUILDER 5 DEVELOPER’S GUIDE Data Acquisition Architectures ............................................................889 The Basic Choices ..........................................................................890 Fetching Data from Many Sources ................................................891 Data Module Designer ........................................................................893 What Are Data Modules? ..............................................................893 Why Use a Data Module? ..............................................................893 How Do I Use a Data Module in My Applications, DLLs, and Distributed Objects?..............................................................895 What Goes in a Data Module? ......................................................896 How Can I Add Properties to My Data Module? ..........................897 How to Use the Data Module Designer ........................................897 Advanced Concepts ........................................................................900 Form Inheritance with Data Modules ............................................900 Handling Uneven Form Inheritance with Data Modules ..............901 How to Avoid Dependence on Specific User Interfaces ................902 How to Work with Application-Specific and Framework Components in Data Modules ....................................................903 Data Modules in Packages ............................................................905 Data Module Designer—Conclusions............................................905 InterBase Express ................................................................................905 Bug Tracker Database Schema ......................................................906 Database Rules ..............................................................................909 Generators, Triggers, and Stored Procedures ................................909 Bug Tracker Implementation..........................................................911 Bug Tracker Wrap Up ....................................................................920 Summary ..............................................................................................921
Part III 15
Interfaces and Distributed Computing DLLs and Plug-Ins 925 Using the DLL Wizard ........................................................................926 Writing and Using DLLs ....................................................................927 Linking DLLs Statically ................................................................928 Importing Functions from a Dynamically Linked DLL ................931 Exporting Classes ..........................................................................936 Using Packages Versus DLLs ..............................................................939 Using SDI Forms in a DLL ................................................................942 Using MDI Child Forms in DLLs and Packages ................................943 Using MDI Child Forms in DLLs..................................................943 Using MDI Child Forms in Packages ............................................948 Using Microsoft Visual C++ DLLs with C++Builder ........................951 Using C++Builder DLLs with Microsoft Visual C++ ........................952 Writing Plug-Ins ..................................................................................953
00 9721 CD-FM
4.6.01
1:58 PM
Page xvii
CONTENTS Anatomy of a Plug-In ....................................................................954 TIBCB5PlugInBase Class ................................................................959 TBCB5PluginManager ......................................................................963 Wrapping Up Plug-Ins....................................................................965 Summary ..............................................................................................965 16
COM Programming 967 Understanding COM Servers and Clients ..........................................968 Outgoing Interfaces and Event Sinks Revisited ..................................969 Writing the COM Server ....................................................................970 Choosing the Server Type ..............................................................971 Choosing a Threading Model ........................................................972 Creating the Server ........................................................................973 Adding a COM Object ..................................................................974 Dissecting the Generated Code ......................................................978 Writing Method Bodies ..................................................................983 Adding Better Error Support ..........................................................985 Implementing a Method That Fires an Event ................................988 Implementing a Custom Interface ..................................................989 Firing Custom Events ....................................................................993 Writing the Proxy/Stub DLL ..............................................................999 Writing the COM Client ....................................................................1006 Importing the Type Library ..........................................................1007 Looking at the Generated C++ Constructions..............................1008 Creating and Using the COM Server Object ..............................1011 Catching Dispinterface-Based Events ..........................................1013 Querying for the Custom Interface ..............................................1016 Writing the Custom Interface-Based Event Sink ........................1017 Recommended Readings....................................................................1021 Summary ............................................................................................1022
17
Going Distributed: DCOM 1023 What Is DCOM? ................................................................................1024 Windows OS Family and DCOM ................................................1025 The DCOMCnfg Utility Tool ............................................................1025 Global Security Settings ..............................................................1026 Per-Server Security Settings ........................................................1028 Field Testing DCOM ........................................................................1031 Creating the Server Application ..................................................1031 Creating the Client Application....................................................1033 Configuring Launch and Access Permissions ..............................1036 Configuring Identity ....................................................................1037 Running the Example ..................................................................1037
xvii
00 9721 CD-FM
xviii
4.6.01
1:58 PM
Page xviii
C++BUILDER 5 DEVELOPER’S GUIDE Programming Security ......................................................................1038 CoInitializeSecurity Function Parameters ..............................1038 Using CoInitializeSecurity ......................................................1040 Understanding DLL Clients and Security ....................................1042 Implementing Programmatic Access Control ..............................1042 Implementing Interface-Wide Security ........................................1044 Using the Blanket ........................................................................1046 Summary ............................................................................................1054 18
One Step Ahead: COM+ 1057 Introducing COM+ ............................................................................1058 COM+ Applications ....................................................................1058 The COM+ Catalog ......................................................................1059 Using COM+ Services ......................................................................1060 Loosely Coupled Events ..............................................................1060 Transactions..................................................................................1062 Synchronization ............................................................................1065 Security ........................................................................................1066 Queued Components ....................................................................1066 Load Balancing ............................................................................1066 Developing and Using COM+ Events ..............................................1067 Creating the COM+ Event Object................................................1067 Installing the Event in a COM+ Application ..............................1069 Creating the Publisher ..................................................................1073 Creating Subscribers ....................................................................1074 Configuring Subscribers ..............................................................1078 Creating a Persistent Subscription................................................1080 Creating a Transient Subscription ................................................1083 Developing and Using COM+ Transactional Objects ......................1093 Creating the Transactional Objects for the Business Layer ........1095 Developing Compensated Resource Managers ............................1105 Creating the Client........................................................................1118 Summary ............................................................................................1119
19
Multi-Tier Distributed Applications with MIDAS 3 1121 Introduction to MIDAS......................................................................1122 MIDAS Clients and Servers ..............................................................1125 Creating a Simple MIDAS Server................................................1125 Examining MIDAS Server Registration ......................................1129 Creating a MIDAS Client ............................................................1130 Using the Briefcase Model ..........................................................1134 Using ApplyUpdates ....................................................................1138 Implementing Error Handling ......................................................1138
00 9721 CD-FM
4.6.01
1:58 PM
Page xix
CONTENTS Demonstrating Reconcile Errors ..................................................1142 Accessing the Server Remotely....................................................1143 Creating a MIDAS Master-Detail Server ....................................1144 Exporting Master-Detail DataSets................................................1147 Creating a MIDAS Master-Detail Client......................................1148 Using Nested Tables ....................................................................1149 Understanding MIDAS Bandwidth Bottlenecks ..........................1152 MIDAS 3 Enhancements ..................................................................1154 TDataSetProvider ........................................................................1154 IProvider Versus IAppServer ......................................................1155 Stateless Data Broker ..................................................................1155 InternetExpress Applications........................................................1161 WebConnection Component ..........................................................1163 Object Pooling ..............................................................................1164 Socket Server................................................................................1166 Object Broker ..............................................................................1169 Deployment ..................................................................................1170 Summary ............................................................................................1171 20
Distributed Applications with CORBA 1173 Introduction to CORBA ....................................................................1174 How CORBA Works..........................................................................1175 Static and Dynamic ......................................................................1175 Always or On-Demand ................................................................1175 Flat or Hierarchical ......................................................................1176 Who Is the Server and Who Is the Client ....................................1176 The Object Request Broker ..........................................................1176 The Basic Object Adapter ............................................................1177 The Portable Object Adapter ........................................................1177 CORBA Versus COM ..................................................................1177 Visibroker Components ....................................................................1177 The Smart Agent ..........................................................................1178 The Object Activation Daemon ....................................................1178 The Console..................................................................................1178 The Interface Definition Language....................................................1178 The interface Keyword ..............................................................1179 The attribute Keyword ..............................................................1180 Methods ........................................................................................1180 Type Definitions ..........................................................................1180 Exceptions ....................................................................................1180 Inheritance ....................................................................................1181 Modules ........................................................................................1181
xix
00 9721 CD-FM
xx
4.6.01
1:58 PM
Page xx
C++BUILDER 5 DEVELOPER’S GUIDE What’s New in C++Builder 5 ............................................................1182 C++Builder Support for CORBA ......................................................1183 Environment Options....................................................................1183 Debugger Options ........................................................................1184 Project Options ............................................................................1184 The CORBA Server Wizard ........................................................1185 The CORBA Client Wizard..........................................................1186 CORBA IDL File Wizard ............................................................1186 CORBA Object Implementation Wizard......................................1187 The Project Updates Dialog ........................................................1188 The Use CORBA Object Wizard..................................................1189 Differences Between C++Builder 4 and C++Builder 5 ..............1190 Implementation Models ....................................................................1191 Inheritance ....................................................................................1192 Virtual Implementation Inheritance..............................................1192 Delegation Model (Tie) ................................................................1192 Poor Man’s CORBA ..........................................................................1193 Summary ............................................................................................1193 21
Microsoft Office Integration 1195 Overview of Integration with Microsoft Office ................................1196 How to Integrate ................................................................................1197 Using TOleContainer ..................................................................1197 Using Automation ........................................................................1199 Using Variants and Automation Objects ......................................1201 Guarding Against Macro Viruses with Automation ....................1203 Using Word Basic ........................................................................1203 Integrating with Word ........................................................................1204 Collections ....................................................................................1204 The Application Object ................................................................1204 Working with Documents ............................................................1205 Getting Text from Word................................................................1209 Putting Objects into Word Documents ........................................1212 Integrating with Excel........................................................................1216 Obtaining the Application Object ................................................1216 Working with Workbooks ............................................................1216 Putting Cells into Excel Worksheets ............................................1219 Getting Cells from Excel..............................................................1221 Using C++Builder 5’s Server Components ......................................1221 The WordApplication and WordDocument Components ..............1223 Vocabulary Revisited ....................................................................1223 Final Thoughts About ATL and OleServers ................................1228 Going Further ....................................................................................1228
00 9721 CD-FM
4.6.01
1:58 PM
Page xxi
CONTENTS Word ............................................................................................1229 Excel ............................................................................................1229 Other Office Applications ............................................................1230 Summary ............................................................................................1232 22
Part IV 23
Using ActiveX Techniques 1233 Understanding Active Server Objects................................................1234 A Step-by-Step Example: Creating Response and Request Objects Via the Active Server Object Wizard ............1235 ASP Session, Server, and Application Objects ............................1243 ASP Objects and WebBroker Support..........................................1243 Redeployment of Active Server Objects ......................................1244 Debugging Active Server Objects ................................................1245 Introducing ActiveForms ..................................................................1246 Building an ActiveForm ....................................................................1246 Deploying an ActiveForm for Use in Internet Explorer....................1249 Setting Options for an ActiveForm ..............................................1249 Connecting to an ActiveForm ......................................................1252 Creating a Data-Aware ActiveForm ..................................................1254 Working with CAB Files and Packages ......................................1257 ActiveForm Updates ....................................................................1258 OCCACHE and Downloaded Program Files ....................................1258 Creating ActiveForms as MIDAS Clients ........................................1259 Using an ActiveForm in Delphi ........................................................1261 Creating Component Templates with ActiveForms ..........................1263 Shell Programming ............................................................................1264 Shell Basics ..................................................................................1264 Retrieving a Folder’s Contents ....................................................1267 Transferring Shell Objects............................................................1269 Summary ............................................................................................1275 Advanced Topics Data Presentation with C++Builder 1279 Presenting Data in Reports ................................................................1280 Understanding the Value of a Report ..........................................1280 Using QuickReport to Produce Reports ......................................1281 Understanding the Philosophy of the Custom Viewer ................1281 QuickReport Custom Viewer Summary ......................................1292 Printing Text and Graphics ................................................................1292 Printing Text ................................................................................1292 Printing Graphics..........................................................................1303
xxi
00 9721 CD-FM
xxii
4.6.01
1:58 PM
Page xxii
C++BUILDER 5 DEVELOPER’S GUIDE Using Advanced Printing Techniques................................................1308 Determining Printer Resolution....................................................1308 Determining the Printable Paper Size ..........................................1308 Determining the Physical Sizes....................................................1309 Determining Printer Drawing Capabilities ..................................1310 How to Print with a Rotated Font ................................................1311 Getting Access to Printer Settings and Setup ..............................1312 How to Get the Default Printer Name..........................................1313 How to Set the Default Printer ....................................................1314 Resetting TPrinter ......................................................................1318 General Information About Accessing DEVMODE Using TPrinter............................................................................1318 Using PRINTER_INFO_2 ................................................................1319 Other Paper-Related Functions ....................................................1325 Working with Jobs........................................................................1334 How to Catch the Pressing of the Print Screen Button ................1336 Printing a Form ............................................................................1338 Creating a Print Preview ..............................................................1338 Using Printer-Related Conversion Routines ................................1339 Other Printer-Related Information ..............................................1341 Creating Charts with the TChart Component....................................1342 Getting Started with TeeChart ......................................................1342 Altering Chart Appearance at Runtime ........................................1344 Interacting with Charts ................................................................1345 Creating Charts Dynamically ......................................................1347 Printing Charts..............................................................................1348 Upgrading to TeeChart Pro ..........................................................1349 Summary ............................................................................................1350 24
Using the Win32 API 1351 Win32 API Versus Win32 Middleware..............................................1352 Brief History of Windows and the API..............................................1353 Win32 API Functional Areas ............................................................1356 Windows Management ................................................................1358 System Services............................................................................1360 Graphical Device Interface ..........................................................1363 Multimedia Services ....................................................................1364 Common Controls and Dialogs ....................................................1366 Shell Features ..............................................................................1369 International Features ..................................................................1370 Network Services..........................................................................1371
00 9721 CD-FM
4.6.01
1:58 PM
Page xxiii
CONTENTS Anatomy and Operation of a Windows Program ..............................1372 WinMain() ....................................................................................1372 Window Handles ..........................................................................1374 Windows Messages ......................................................................1374 Real-World Examples Using the API ..............................................1377 Launching an Application Within a Program ..............................1378 Fundamental File I/O....................................................................1382 Using the Magic of Shell..............................................................1393 Implementing Multimedia Services ............................................1406 Using Globally Unique Identifiers (GUIDs)................................1410 Determining System Information ................................................1411 Flashing a Notification ................................................................1423 Adding System Support................................................................1427 Animating Effects ........................................................................1429 Shaping Your Applications ..........................................................1432 Writing Control Panel Applets the Old-Fashioned Way ..............1442 Summary ............................................................................................1455 25
Multimedia Techniques 1457 The Graphical Device Interface (GDI) ..............................................1458 The Windows API and the Device Context..................................1459 Understanding TCanvas: The C++Builder Interface ....................1459 Customizing a Drawing................................................................1462 An Analogue Clock Example ......................................................1464 Image Support....................................................................................1465 The Windows Bitmap Object ......................................................1466 The TBitmap Class ........................................................................1466 JPEG Images ................................................................................1467 GIF Images ..................................................................................1468 PNG Images..................................................................................1469 Image Processing ..............................................................................1472 Displaying and Obtaining Image Information ............................1473 Accessing Individual Pixel Values Using TCanvas->Pixels ........1474 Image Generation ........................................................................1475 Fast Access to Pixel Value Using ScanLine ................................1477 Point Operations: Thresholding and Color/Grayscale Inversion ....................................................................................1478 Global Operation: Histogram Equalization..................................1480 Geometrical Transformation: Zoom ............................................1483 Spatial Operation: Smoothing and Edge Detection ....................1487
xxiii
00 9721 CD-FM
xxiv
4.6.01
1:58 PM
Page xxiv
C++BUILDER 5 DEVELOPER’S GUIDE Audio Files, Video Files, and CD Music ..........................................1489 The Media Control Interface ........................................................1489 The Waveform Audio Interface ....................................................1496 Concluding Remarks on the Waveform Audio Interface ............1504 Summary ............................................................................................1504 26
Advanced Graphics with DirectX and OpenGL 1505 Introduction to OpenGL ....................................................................1506 OpenGL Versus Direct3D ............................................................1507 The OpenGL Command Structure ..............................................1507 Drawing Loops in C++Builder Using OnIdle() ..........................1507 Using OpenGL ..................................................................................1508 Stage 1: OpenGL Initialization ....................................................1508 Stage 2: Setting Up a Rendering Environment with Lighting and Shading ................................................................1515 Stage 3: 3D Transformations........................................................1518 Stage 4: Drawing Primitives ........................................................1520 Stage 5: Flipping Surfaces............................................................1530 An Example OpenGL Program ....................................................1530 OpenGL Conclusion ....................................................................1531 OpenGL References ....................................................................1531 Introduction to DirectX......................................................................1532 COM Basis of the DirectX API....................................................1532 Non-Object DirectX Functions ....................................................1533 Using DirectDraw ..............................................................................1533 Initialization of a DirectDraw Object ..........................................1533 Adjusting Display Settings for DirectDraw ................................1535 Drawing Surfaces ........................................................................1537 Using the GDI on DirectDraw Surfaces ......................................1539 Loading Bitmaps into a Surface ..................................................1541 A DirectDraw Example Program ................................................1547 DirectDraw Conclusion ................................................................1547 Using DirectSound ............................................................................1547 Initializing a DirectSound Object ................................................1548 Creating a Secondary Buffer ........................................................1549 A DirectSound Example Program—A Multiple Sound Player ..1556 Taking DirectX Further......................................................................1556 DirectX References............................................................................1557 Summary ............................................................................................1557
00 9721 CD-FM
4.6.01
1:58 PM
Page xxv
CONTENTS
Part V
C++Builder Application Deployment
27
Creating Help Files and Documentation 1561 Technical Writing 101—Ten Quick Steps to Better Writing ............1562 Types of Documentation....................................................................1563 Strategies for Online Documentation ................................................1564 Approaches to Help ......................................................................1565 Help Formats......................................................................................1568 WinHelp Format Help Files: The Windows Standard ......................1570 Help-Authoring Tools ..................................................................1571 Context-Sensitive Help ................................................................1572 The MS Help Workshop ..............................................................1573 Adding What’s This? Help to C++Builder ..................................1579 Expanding Your Help Project Using Advanced Features ............1580 Microsoft HTML Help Files..............................................................1581 Help Properties and Methods in the VCL ........................................1583 Help Properties ............................................................................1583 Help Methods ..............................................................................1583 Events ..........................................................................................1587 Resources for the Help Author ..........................................................1587 Books ............................................................................................1587 Help-Authoring Tools Available on the Internet ..........................1588 Summary ............................................................................................1592
28
Software Distribution 1593 Language Internationalization and Localization ..............................1594 Overview of Language Internationalization ................................1594 The Localize Application ............................................................1595 Things to Remember ....................................................................1601 Resource DLL Wizard ......................................................................1602 How Does It Work? ......................................................................1602 How to Create a Resource DLL ..................................................1602 How to Test It ..............................................................................1605 Other Files and Programs to Ship......................................................1606 Your Application Files..................................................................1606 Distribution Steps ........................................................................1609 Copyrighting and Software Licensing ..............................................1609 Copyrighting ................................................................................1609 Software Licensing ......................................................................1611 Software Protection............................................................................1611 Protecting Your Application ........................................................1612 Protecting Your Application with Third-Party Components ........1612
xxv
00 9721 CD-FM
xxvi
4.6.01
1:58 PM
Page xxvi
C++BUILDER 5 DEVELOPER’S GUIDE Protecting Your Application with Other Types of Components ..............................................................................1614 Some Final Thoughts on Software Protection ............................1615 Shareware ..........................................................................................1615 Shareware and How to Protect It..................................................1616 Implementing Shareware Protection Methods ............................1618 Shareware Methods in a Nutshell ................................................1618 Distribution and Marketing Via the Internet......................................1618 Web Sites ......................................................................................1619 Customer Support ........................................................................1619 Advertising ..................................................................................1619 Free Banner Ads ..........................................................................1620 Accepting Credit Cards and Providing Unlock Codes ................1621 Internet Marketing Hints and Tips ..............................................1622 Summary ............................................................................................1623 29
Software Installation and Updates 1625 Install and Uninstall ..........................................................................1626 Installation Program Creators ......................................................1626 Install Maker ................................................................................1627 Uninstalling ..................................................................................1630 CAB and INF Files ............................................................................1632 About CAB Files ..........................................................................1632 About INF Files............................................................................1635 About Internet Packages ..............................................................1640 Versions, Updates, and Patches ........................................................1643 Versions ........................................................................................1643 Updates for Application Improvements ......................................1644 Patches ..........................................................................................1646 Patch Maker..................................................................................1647 Some Tips on Updates and Patches..............................................1649 Version Control and TeamSource ......................................................1649 Who Should Use TeamSource? ....................................................1650 Why Should TeamSource Be Used? ............................................1650 When Should TeamSource Be Used? ..........................................1651 Where Can TeamSource Be Used? ..............................................1651 How Is TeamSource Used? ..........................................................1651 TeamSource Windows ..................................................................1657 Version Controllers ......................................................................1660 Bookmarks....................................................................................1661 Locks ............................................................................................1661
00 9721 CD-FM
4.6.01
1:58 PM
Page xxvii
CONTENTS Using InstallShield Express ..............................................................1662 Installing InstallShield..................................................................1663 Getting Started in InstallShield ....................................................1663 Testing ..........................................................................................1671 Summary ............................................................................................1671
Part VI 30
Knowledge Base Tips, Tricks, and How Tos 1675 Making the Enter Key Simulate the Tab Key....................................1676 The Solution ................................................................................1676 Explanation of the Code ..............................................................1677 Some Pitfalls ................................................................................1681 Tab Key Simulation Wrap Up ......................................................1681 Determining the OS Version ..............................................................1682 The Solution ................................................................................1682 The Code ......................................................................................1683 Determining the OS Version Wrap Up ........................................1684 Programming Using Floating-Point Numbers ..................................1684 Background ..................................................................................1685 Working with Numbers ................................................................1686 Performing Addition and Subtraction ..........................................1687 Performing Formulaic Chains of Arithmetic................................1691 Comparing Data............................................................................1691 Floating-Point Numbers—Closing Remark ................................1692 Implementing Splash Screens............................................................1692 The WinMain() Function ..............................................................1692 Creating a Splash Screen..............................................................1694 Preventing More than One Instance of an Application from Running ..................................................................................1696 The Solution ................................................................................1696 The Code ......................................................................................1697 Conclusion ....................................................................................1702 Working with Drag-and-Drop............................................................1702 The Solution ................................................................................1702 The Code ......................................................................................1702 How Does It Work? ......................................................................1705 Wrapping Up Drag-and-Drop ......................................................1707 Capturing the Screen..........................................................................1707 How Windows Handles Windows ................................................1707 The Solution ................................................................................1708 Capturing Screens Wrap Up ........................................................1712
xxvii
00 9721 CD-FM
xxviii
4.6.01
1:58 PM
Page xxviii
C++BUILDER 5 DEVELOPER’S GUIDE Implementing a TJoyStick Component ............................................1713 Creating a Windows System Monitor-Like Application ..................1726 A Look at Windows System Resources ......................................1726 The Solution ................................................................................1728 System Monitor Wrap Up ............................................................1735 Examining a Soundex Application ....................................................1735 The Solution ................................................................................1736 Using Tree View Components ..........................................................1743 Tree View Basics ..........................................................................1744 Adding Nodes ..............................................................................1744 Using Glyphs ................................................................................1747 Navigating Tree Views ................................................................1749 Accessing Nodes ..........................................................................1750 Finding Nodes ..............................................................................1751 Displaying Node Counts ..............................................................1752 Moving Nodes Up and Down ......................................................1754 Implementing Drag-and-Drop ......................................................1755 Modifying a Node ........................................................................1757 Deleting a Node............................................................................1759 Supporting Undo and Redo Deletion ..........................................1760 Save a Tree (For the Morning After)............................................1763 TTree Wrap Up ............................................................................1763 Implementing an Icon Extraction Utility ..........................................1764 Creating a Windows Explorer-Like Application ..............................1773 Investigating Windows Shell Functions and Interfaces................1773 The Solution ................................................................................1774 Windows Explorer Wrap Up ........................................................1781 Working with NT Services ................................................................1781 The SendMsg Program ................................................................1781 The Stickums Service ..................................................................1784 The Stickem Client Program ........................................................1788 Windows Services Wrap Up ........................................................1789 Using Cryptography ..........................................................................1789 The Solution ................................................................................1790 File Encoding................................................................................1793 File Decryption ............................................................................1799 Creating a World Daylight Clock ......................................................1801 Special Supplement for Non-Believers ........................................1807 Summary ............................................................................................1808
00 9721 CD-FM
4.6.01
1:58 PM
Page xxix
CONTENTS 31
Part VII A
A Real-World Example 1809 Examining a World Wave Statistics Program ....................................1810 Examining the Source Code ..............................................................1811 Header File math.h ......................................................................1812 Header File mapunit.h ................................................................1812 Header File wavedata.h ..............................................................1813 Source Code File about.cpp ........................................................1813 Examining the Code for TMainUnit ..................................................1814 Making Some Improvements ............................................................1819 Summary ............................................................................................1821
Appendix Information Sources 1825 Borland Web Sites..............................................................................1826 Borland Community Web Site......................................................1826 Borland Main Web Site ................................................................1827 CodeCentral ......................................................................................1828 Discussion Lists and Forums ............................................................1830 Web-Based Forums ......................................................................1830 Email Discussion Lists ................................................................1831 Newsgroups........................................................................................1831 Web Sites ..........................................................................................1833 How-Tos and Technical Articles ..................................................1834 Component Repositories ..............................................................1834 Books and Magazines ........................................................................1835 C++Builder Books........................................................................1836 General C++ Books ......................................................................1837 Magazines ....................................................................................1837 Conferences and User Groups ..........................................................1838 Index
1839
xxix
00 9721 CD-FM
4.6.01
1:58 PM
Page xxx
About the Authors Major Authors Jarrod Hollingworth Jarrod has been professionally programming since 1993. He is now running his own business, Backslash (http://www.backslash.com.au), developing software applications for the Internet and key business sectors and working as a software development consultant. He has a solid background in C/C++ programming in the telecommunications industry and assisted in the development of the world’s first live operator–answered GSM (digital mobile) short-messaging system. Starting in 1985 as a self-taught hobbyist programmer in BASIC and Assembly, he moved to Pascal and C/C++ through completion of a bachelor of science degree in computing at Deakin University in Australia. His professional roles in software development have ranged from programmer to software department manager. With several years of experience in C++Builder and Delphi and having worked on project teams using Microsoft Visual C++, he believes that with few exceptions C++Builder is the best tool for developing Windows applications. Jarrod lives in Melbourne, Australia, with his wife, Linda. His other major interests include traveling and cycling. Jarrod can be contacted at
[email protected].
Dan Butterfield Dan is currently writing mathematical modeling and geographical information system (GIS) software for environmental applications in the Aquatic Environments Research Centre (AERC) at the University of Reading in the UK. As sole software developer for the research center, Dan works closely with colleagues to provide implementations of ground-breaking water quality modeling and data visualization software. INCA (Integrated Nitrogen in Catchments), the latest incarnation of an original nitrogen model, is in use worldwide and is undergoing continual development. Dan started programming in BASIC at age 12 and has programmed professionally in REXX, Fortran, Pascal, C, and now C++. All of Dan’s development work over the past two years has been exclusively with Borland C++Builder.
Bob Swart Bob Swart (aka Dr. Bob—http://www.drbob42.com) is a senior technical consultant using Delphi, C++Builder, and JBuilder (and soon Kylix) for TAS Advanced Technologies (http://www.tas-at.com) in Best, The Netherlands. Bob is a freelance technical author for
00 9721 CD-FM
4.6.01
1:58 PM
Page xxxi
xxxi
The Delphi Magazine, Delphi Developer, UK-BUG NewsLetter, and SDGN Magazine. He is a coauthor of The Revolutionary Guide to Delphi 2, Delphi 4 Unleashed, and C++Builder 4 Unleashed. Bob has spoken at Borland conferences all over the world.
Jamie Allsop Jamie lives in Northern Ireland. Mostly self-taught, he has used a variety of languages, but C++ is his language of choice. He has used C++Builder since it was first released, and it is his preferred development tool. He has a degree in electronic engineering and is currently doing research. He also runs his own software company, Shiying, with his wife and has developed components for communication and real-time DSP applications. Other interests include football (the using-feet kind) and badminton.
Contributing Authors Rob Allen Rob lives in London, UK. He has a degree in electronic engineering but has spent the last five years programming with Borland C++ 4.5 and 5 and C++Builder 3. Rob has experience writing test and measurement tools for the mobile phone industry.
Khalid Almannai Khalid lives in Bahrain. He started programming with Borland C++ 4.5, and his knowledge of programming languages includes C, C++, BASIC, and Delphi. He has two years of experience with C++Builder.
Drew Avis Drew Avis is a technical writer specializing in online documentation. He lives in Merrickville, Ontario, and currently works for Nortel Networks. Drew has worked for small and large software companies, and he has developed and taught a technical writing course for engineers at the University of Calgary. In his spare time Drew brews beer, plays hockey, and works on his homebrew recipe software StrangeBrew.
Jay Banks Jay lives in the UK. He has been a programming enthusiast since he was 11 and has programming experience in a number of areas, including accounting, machine control, security, components, games, educational, and databases. His C++Builder experience is varied.
00 9721 CD-FM
4.6.01
1:58 PM
Page xxxii
Eduardo Bezerra Eduardo lives in Rio de Janeiro, Brazil. He has been programming for 19 years and has extensive experience in C++ development. Eduardo started programming with Borland Turbo C and has worked with all Borland C/C++ compilers up to C++Builder. He owns a small company specializing in consulting services and development for business areas such as the Internet and telecommunications. He has been working with COM for four years, integrating systems and creating solutions for distributed environments.
Phillip H. Blanton II Phillip attended the University of Northern Colorado, where he studied physics and computer science. He has been programming personal computers with Borland tools since 1987. Over the past 13 years he has worked in a number of technical roles, including network administrator, IS department director, database application developer, and network security specialist. He is currently a senior software engineer with TurboPower Software in Colorado Springs. He lives in the mountains surrounding Woodland Park, Colorado, with his wife Mary Ann, two daughters Daly and Sydney, and Harley the Wonder Dog. You can reach him via email at
[email protected].
Joe Bonavita Joe lives in Connecticut and has been programming for 14 years, three of those years in C++Builder. Joe started programming when he was 14 on a Commodore 64 and is a selftaught programmer. He graduated to the PC, then to BASIC, Assembler, and C++. Joe started using C++Builder beginning with version 1. Thanks to his wife, who gives him the support needed to keep moving forward in the ever-changing field of programming, he is learning other languages and contributing to books such as this one. Joe believes that books like this are very beneficial to self-starters.
J. Alan Brogan Alan lives in Kerry, Ireland. He has been programming and teaching for more than 10 years and is currently leading a team developing software within the telecommunications industry. Alan has used other languages but prefers the simplicity and elegance of C and C++. He has always preferred Borland’s IDEs and still uses Turbo C, but he spends most of his programming day with C++Builder.
00 9721 CD-FM
4.6.01
1:58 PM
Page xxxiii
Mark Cashman Mark is a professional software developer with experience in a variety of industries, ranging from insurance to manufacturing, to geographic information systems for bulk product delivery. His specialties include computer/human interaction, relational databases, component-based software, object-oriented development, and Web site/Web software development, including his own site, The Temporal Doorway, whose C++Builder section can be found at http://www.temporaldoorway.com/programming/index.htm. He has been a methodology consultant, a developer, and a manager and is currently Senior Software Developer for VTechnologies, LLC, a vendor of shipping-oriented middleware. Mark is a member of Borland TeamB, an association of official but unpaid newsgroup support people, selected for their knowledge of Borland products and willingness to help other developers. He is also an awardwinning artist, a published author of science fiction (currently working on his third novel) and nonfiction (including several articles for C++Builder Developer’s Journal), a composer of computer-based fusion music, and a rock climber with several first ascents to his credit.
Damon Chandler Damon has been programming for more than 15 years. Mostly self-taught, he followed a common path to C++ programming: GW-BASIC, Pascal, then C++. Damon is an engineer by trade and a programmer at heart. He is currently working in the Visual Communications Lab at Cornell University, where his research primarily centers around wavelet image compression. C++Builder is his tool of choice, and he has recently been made a member of TeamB.
Jeppe Cramon Jeppe lives in Copenhagen, Denmark. He has been programming for seven years, starting out on Pascal, then moving on to C++, Visual Basic, Java, and C#. Jeppe has been using C++Builder the last four years and has recently started working with XML, ASP, DHTML, COM, and .NET programming. Jeppe holds an engineering degree in electronics and computer science. Besides running a small consulting firm, Jeppe also contributes to the Bytamin-C Web site (http://www.bytamin-c.com) and has developed a free WinZip clone—Jzip—and an arcade game—B.U.G.S.—for OS/2 and Windows. Jeppe is also an enthusiastic skier and drummer in his sparse spare time.
Mark Davey Mark lives in Hampshire, England. He has been writing software professionally since his teens and has been using C++Builder for two years. He has been mostly involved in writing realtime embedded control systems for broadcasting applications with leading UK broadcast engineering companies and is currently developing radio communication systems. Mark also has a
00 9721 CD-FM
4.6.01
1:58 PM
Page xxxiv
private enterprise in data logging systems for the motorsport industry, developing exclusively with C++Builder. He is deeply interested in music, art, and technology. He is shortly to be married to Sarah.
Paul Gustavson Paul lives in Virginia and is a senior systems engineer for Synetics, Inc. (http://www. a U.S.-based company providing knowledge management, systems engineering, and enterprise management services. Paul supports a wide variety of advanced distributive simulation efforts within the DoD community and is an experienced software developer specializing in C++Builder. He also is a partner in SimVentions (http://www.simventions.com), an upstart company developing and leveraging existing technologies and techniques to create innovative applications and solutions that engage the mind and further knowledge. Paul has been developing applications for the Windows environment since the introduction of Windows 3.1 (1993), and he has published and presented over a dozen technical papers for the Simulation Interoperability Standards Organization (http://www.sisostds.org). synetics.com),
John MacSween John graduated from Glasgow University with an honours degree in naval architecture and ocean engineering. He presently works for Henry Abram & Sons Ltd, a project cargo and heavy lift shipping company in Glasgow, Scotland. John has been programming since the age of 14 and has used BASIC, Fortran, and C++. He has been programming in C++Builder for approximately one and a half years and uses it to create various in-house engineering applications. John may be contacted at
[email protected] or http://www.redrival.com/mandtsoftware/.
Stéphane Mahaux Stéphane runs his own software consulting company, Hyperian Development Solutions (http://www.hyperian.ab.ca), in Edmonton, Canada. He started programming before the Windows 3 era and has been programming professionally for more than 10 years. He has been using C++Builder since version 1. Stéphane also has lived in France, where he managed a business specializing in database tools. He wrote a monthly column in Point DBF magazine about database programming in various development tools.
William Morrison Hooked on Borland products since being introduced to Turbo Pascal 7 in high school, Bill has been programming professionally with C++Builder and Delphi for more than three years. Bill has written predictive dialers and standard business applications using C++Builder and is
00 9721 CD-FM
4.6.01
1:58 PM
Page xxxv
experienced with ISAPIs, APIs, and C/S database design. He assists new C++Builder and Delphi users through the Undernet IRC help channels and can be seen occasionally contributing on the various Borland Usenet groups. Bill is currently vice president of Software Development for CXC Consulting (http://www.cxcca.com), located in sunny Southern California. Bill wishes to thank Jason Wharton (IBObjects) and Jeff Overcash (IBX) for their assistance with the InterBase sections in this book, showing just what a great group of programmers InterBase has supporting it.
Ionel Munoz Ionel lives in Quebec. His current occupation is as a senior software analyst at EXFO, a leading manufacturer of fiber optics test equipment. His job involves developing architectures and frameworks, most of them based on COM/DCOM. Ionel started programming in Turbo Pascal in 1990 and C++ in 1992, and he has used C++Builder since version 1. He has developed applications in many areas, including games, components, Java applets, client/server databases, data acquisition systems, and multimedia. He has been developing with COM since 1995 and is experienced in using ATL in both VC++ and C++Builder. He has contributed to Borland’s CodeCentral source code database, with several COM-related examples. His interests beyond computer science are traditional karate, books, and music. Ionel has a wife, Sylvia, and a daughter, Marietta.
Jean Pariseau Jean works as a chef at a prestigious New England country club while attending college at the Community College of Rhode Island, where he’s about to receive his associates degree in engineering. Jean has been programming for about 14 years, starting on a Commodore 64 and working up through the Amiga platform and now Windows-based machines. Mostly self taught, Jean works with C++, Pascal/Delphi, Assembler, Lisp, and Java. Jean’s programming interests revolve around computer algebra, numerical methods, computational fluid dynamics, and compiler design.
Pete Pedersen Pete lives in Logan, Utah, and has been programming professionally for over 30 years. He has used Borland’s tools for about eight years, and C++Builder since version 1. During his career, he has been an international consultant and the founder of a software company (BlueLine Software) and has written articles for trade publications. He is currently employed by Spiricon, a leader in laser diagnostics. When not working, he enjoys spending time with his family. He and his nine-year-old son, Cameron, are collaborating on a programming book for kids, using C++Builder.
00 9721 CD-FM
4.6.01
1:58 PM
Page xxxvi
Ruurd F. Pels Ruurd works in the Netherlands as an IT consultant for TAS Advanced Technologies B.V. His main area of expertise is software engineering, particularly in C++. He is a regular contributor to Dr. Bob’s C++Builder Gate (http://www.drbob42.com/Cbuilder/) and occasionally publishes reviews and articles. He can be reached at
[email protected]. Ruurd is married to Angelien and the father of two sons, Ruben and Daniël.
Sean Rock Sean lives in Bolton, UK. He is originally from San Diego, California, but has lived in the UK for the past five and a half years. Sean started programming in college using Pascal and has taught himself Delphi and C/C++. Sean uses computer programming primarily as a hobby but does take on freelance work for local companies. He has been using C++Builder for about two years and just recently started the Component Writer’s Guide Web site, dedicated to writing VCL components, which can be found at http://www.componentwriter.co.uk.
Simon Rutley-Frayne Simon lives in Devon, UK. He began programming with C++Builder just over two years ago and soon after started Casimo Software (http://www.casimosoftware.co.uk), developing shareware software and components. Simon runs his own computer consultancy business and is the Components/Applications and Books editor of TheBits (http://www.thebits.org), where he is responsible for component and book reviews and updates.
Vikash Shah Vikash lives in Middlesex, England. Since earning his degree in mathematics and computer science, he has gained three years professional C++ experience, including two years with C++Builder.
Malcolm Smith Malcolm lives in Australia. He is a self-taught programmer working as an analyst programmer, developing customized MIS solutions for the printing industry, and device drivers for monitoring and surveillance equipment in the security industry. He also runs his own business, MJ Freelancing, developing encryption, anti-piracy, and other tools and components.
00 9721 CD-FM
4.6.01
1:58 PM
Page xxxvii
Keith Turnbull II A graduate of Michigan State University, Keith has been in network programming since 1991. He has worked on a range of products, from online games to insurance enrollment software. He is currently the vice president of client/server development for Intercanvas Design, Inc. Keith lives in Des Moines, Iowa, with his wife, two dogs, three cats, and four computers.
Chris Winters Chris lives in Richmond, Virginia. He has been programming for six years, two years professionally. Although fluent in C/C++, Chris has used BASIC, HTML, Java, Assembly, MS Access, and Delphi. He started with Turbo C++ (DOS) and has been using C++Builder since version 1. Chris currently works for PSINet, one of the world’s largest and most experienced providers of IP-based communications services for business. He has two kids, Lauren Ashley and Collin Mason. He also writes system utilities and shareware programs and experiments with new Win32 APIs. You can visit him at http://www.encomsysware.com.
William Woodbury Bill has been programming since he was 12. He has used a variety of languages, including ADA, BASIC, Pascal, Java, C/C++, and Assembly, and he currently uses C++Builder. He has written graphics applications, games, and networking applications.
Siu-Fan Wu Siu-Fan obtained his bachelor of science degree in physics and his Ph.D. in electronic and electrical engineering from the Univerity of Surrey in the UK. He worked for the Canon Research Centre (UK) as a research scientist on sound field visualization and then as a lecturer at Singapore Polytechnic. Currently he is a lecturer at the Hong Kong Institute of Vocational Education, teaching mainly microprocessors and instrumentation. His research interests include image processing, compression, and retrieval. He has been programming with Borland C and C++Builder for about nine years.
Yoto Yotov Yoto Yotov is currently studying in Montreal. Often working with C++Builder, he has continuously explored it since its first appearance. He has published articles in various technical journals and Web sites.
Zexiang Wu Zexiang Wu has been programming with Borland C++ for ten years. Her recent work has focused on interface programming. Away from work, she enjoys backpacking, classical and folk dancing, and she especially enjoys sampling food from different countries; her favorites are from southern China where she originates.
00 9721 CD-FM
4.6.01
1:58 PM
Page xxxviii
Dedications Jarrod Hollingworth I dedicate this book to my wife, Linda. Throughout the many long days and late nights, her love, support, understanding, and acceptance of my constant phrase “another 15 minutes” (an hour and a half in the real world) have made this book possible.
Dan Butterfield To my family.
Bob Swart For Yvonne, Erik, and Natasha.
Jamie Allsop To Wenmay (Wu Ze Xiang), who never lost faith.
00 9721 CD-FM
4.6.01
1:58 PM
Page xxxix
Acknowledgments Jarrod Hollingworth First I’d like to thank Dan Butterfield. From concept to completion, Dan shared the author-side organizational tasks with me. With more than 30 contributing authors, these tasks were very demanding, and the time and effort that Dan invested in them is extremely appreciated. I’m sure that Dan would agree that it was quite a challenge! This book has opened my eyes to the fact that the publishing process is very involved indeed. As the acquisitions editor, Carol Ackerman took the book onboard and managed the manuscript submissions and the overall schedule. Robyn Thomas was the development editor for this book. Her eagle eye for quality and content-related issues ensured that the book as a whole is more than the sum of its parts. It was a pleasure working with both Carol and Robyn. I’d also like to thank technical editors Paul Strickland, John Thomas, Peter Nunn, and Eamonn Wallace for their attention to detail, copy editors Gene Redding and Pat Kinyon (who, with their superior knowledge of English, improved the grammar in just about every paragraph), project editor Andrew Beaster, and all other staff at Macmillan. For their assistance with various issues in writing my topics, I’d like to thank Charlie Calvert, Michael Swindell, Tim Del Chiaro, John Wiegley, Lee Cantey, Maurice Barnum, David Marancik, Karen Giles, John Kaster, and David Intersimone at Borland and Kent Reisdorph and Per Larsen at Turbopower Software Company. Finally I’d like to thank each and every author in this book, but in particular Bob Swart, Jamie Allsop, Ionel Munoz, and Vikash Shah, who showed exceptional commitment and enthusiasm. With such a large breadth of experience, each author has donated a piece of his knowledge to make this book an invaluable resource for C++Builder developers.
Dan Butterfield I would like to thank (in no particular order): The directors of the AERC, Professor Paul Whitehead and Dr. Penny Johnes, for their patience and understanding on those occasions when book deadlines interfered with my day job. My colleagues and friends, for their interest and support, but especially Brian Cox, Andrew Wade, Hannah Prior, Steve Gurney and of course Cam Sans, who helped keep me sane. Matt Roberts and Andrew Burns for invaluable Web site help and advice. Erika Meller and Heather Browning for their image manipulation and graphic design skills. Nicola Tuson and Joan Bachelor for helping out with online chat transcriptions.
00 9721 CD-FM
4.6.01
1:58 PM
Page xl
Everyone at Macmillan, but especially Carol Ackerman, Robyn Thomas, Andrew Beaster, and Paul Strickland, who all had to work incredibly hard to make this book a reality. Finally, a huge thank you to Jarrod for getting this whole thing started (and for all those late night/early morning Internet chats ;o), and to all the authors involved—your commitment and patience astounded me daily. Thanks guys!
Bob Swart I need to thank Yvonne for putting up with me writing yet another set of chapters. The phrase “almost done” slowly lost its meaning to her. Also, thanks to Jarrod and Dan for putting this book together—without you, it wouldn’t be the same.
Jamie Allsop It goes without saying that I am eternally grateful to both Jarrod and Dan. I want to thank you for taking on a task that few can comprehend the enormity of. Because you believed that a book could be written, I (and the other authors) also believed it could be done. I would also like to thank you for your continued encouragement throughout the project; it made the long hours I spent writing and coding worth it and even helped get some chapters finished. Thank you for helping me realize a dream. I want to thank all the authors of the book; if any one of you had not written the sections you did, the book would never have made it to maturity. I would like to thank all the editors at Sams for the excellent work that they put into the book to ensure it is of high quality. I especially would like to thank development editor Robyn Thomas for all her heading suggestions and comments that greatly helped to shape the sections that I wrote. I would also like to thank Paul E. Strickland, one of the technical editors, for his comments and suggestions. Gene Redding and Pat Kinyon also deserve a mention for the excellent work they put into copy editing the chapters I was involved with. Your attention to detail is incredible. I would like to thank my family and friends for their support, patience, and understanding throughout the time I have been involved in the book, notably my twin brother Kristin, my mum Norah, my dad Terry, and my friends Hong and Kendo. Finally, and most importantly, I would like to thank my wife, Wenmay, who supported and cared for me throughout the writing of the book. She continually encouraged me and didn’t mind when I had to put the book first; believe me, that happened very often! Without her, my contribution would surely have been much smaller.
00 9721 CD-FM
4.6.01
1:58 PM
Page xli
Tell Us What You Think! As the reader of this book, you are our most important critic and commentator. We value your opinion and want to know what we’re doing right, what we could do better, what areas you’d like to see us publish in, and any other words of wisdom you’re willing to pass our way. As an Associate publisher for Sams, I welcome your comments. You can fax, email, or write me directly to let me know what you did or didn’t like about this book—as well as what we can do to make our books stronger. Please note that I cannot help you with technical problems related to the topic of this book, and that due to the high volume of mail I receive, I might not be able to reply to every message. When you write, please be sure to include this book’s title and author as well as your name and phone or fax number. I will carefully review your comments and share them with the author and editors who worked on the book. Fax: (317) 581-4770 Email:
[email protected] Mail:
Michael Stephens Sams Publishing 201 West 103rd Street Indianapolis, IN 46290 USA
00 9721 CD-FM
4.6.01
1:58 PM
Page xlii
01 9721 intro
4.19.01
8:44 AM
Page 1
Introduction This has been an extremely interesting project on which to work. Our goal seemed simple—to produce a new book for C++Builder 5 that covered not only material new to version 5, but also techniques and topics not covered anywhere else. The book was born on “The Bits” (http://www.thebits.org) C++Builder technical discussion list with an email from Jarrod Hollingworth in mid-November 1999: Well I’ve just returned from the Australia & New Zealand BorCon99 and it was fantastic. They showed a lot of great enhancements to all products and the tutorials and sessions were very informative…great stuff. I don’t think that it’s likely that there will be a C++Builder 5 Unleashed book… This revelation was a disappointment to everyone subscribed to The Bits list because not only have the Unleashed books proved invaluable resources, but they are often the only readily available C++Builder reference books (the bundled Borland “Teach Yourself …” and “Developer’s Guide” manuals aside). It gradually became clear that several list subscribers had been considering writing articles on their particular areas of expertise, and so the project was born. Our first task was to decide what kind of book we should write and what topics the C++Builder community would like to see in it. To this end, the original Web site (dubbed “The C++Builder Book Writers’ Guild”) was set up, complete with online survey. We advertised the survey on the most active C++Builder discussion lists and newsgroups. The results from this survey and from online discussions (which can be found on the book’s Web site at http://www.bcb5book.force9.co.uk) helped shape the book. So, here we are with the final product. The book has been written by 34 authors from all over the world, in countries including Australia, Bahrain, Brazil, Canada, Denmark, Hong Kong, Ireland, the Netherlands, the UK, and the U.S. Each author contributed topics in his area of expertise and managed this task using email, online chats, and the Web site (and the occasional telephone call). All of the authors have full professional and personal lives and have somehow managed to work on the book in the little spare time that they have. The majority of the authors have little or no professional writing experience, though you may recognize the names of several authors from other C++Builder and Delphi books, as TeamB newsgroup members, or hosts of C++Builder-related Web sites. It has, of course, been very hard work. At the time of writing, the project organizers have collectively spent well over 600 hours, sent over 2,000 emails, and received over 3,500 emails on organizational matters alone. It has been an incredibly rewarding experience, and hopefully, the brief history of the project given here will persuade you that there is nothing magical about
01 9721 intro
2
4.19.01
8:44 AM
Page 2
C++BUILDER 5 DEVELOPER’S GUIDE
technical book writing—you can do it, too. We hope that we have created a book that users of all versions of C++Builder will find useful in the development of all types of applications. We have worked hard to include topics and techniques not covered in any other book and have done our best to cover the majority of features new to C++Builder 5. Above all, we hope that, through the unique way in which the book has been written, we have adhered to the C++Builder/Delphi ethos: sharing of knowledge.
Important Things to Note Because of the way this book was written, with so many authors and over a relatively short time period, there are bound to be differences in writing styles between, and perhaps even within, chapters. We (the authors and a team of editors at Sams) have all worked hard to reduce the impact of this, but it is bound to be obvious in places. As with all technical books, and despite our best efforts, it is inevitable that there will be the occasional error in the text and accompanying program code. In light of this, we shall maintain a list of errata on the book Web site at http://www.bcb5book.force9.co.uk and on the Sams Web site at http://www.samspublishing.com. You can also email bug reports and general queries/comments to
[email protected].
The Companion CD-ROM The companion CD-ROM contains all of the example code and C++Builder projects from the book. The code is organized by chapter and can be accessed from a custom-built interface. Some of the chapter folders also contain README.TXT files that provide important information about the projects in that chapter. These include chapters 13, 15, 16, 18, and 19. There are also many freeware, shareware, demo and trial components, and applications that should be of interest to C++Builder users. These may also be viewed from the interface to the CD-ROM. To ensure that the CD-ROM list of contents is up to date, it is supplied as a README.TXT file in the CD-ROM’s root directory.
A Word of Thanks During the course of the project, the list of contributing authors changed regularly as other commitments took priority and topics were added or altered. We’d like to take this opportunity to thank everyone who volunteered to help but were unable to see the book through to completion. We are particularly grateful to Rick Malik, the creator (and host) of the original book Web site, who put in a lot of time and effort during the initial stages of the project.
01 9721 intro
4.19.01
8:44 AM
Page 3
INTRODUCTION
Who Should Read This Book? This book is not a C++ primer, nor is it a tutorial on using C++Builder, the application. Rather, it is a guide to using C++Builder to create better, larger, more complex applications, to help expand your current C++Builder skills, and to investigate the features new to C++Builder 5. If you already have experience developing applications with C++Builder, are looking to upgrade from version 4 to version 5, or want to build on your current knowledge, this book is for you. That said, there is a natural, rapid progression through most of the chapters and through the book as a whole. This should even make the book useful to C++Builder beginners as, although the book was originally intended to be for intermediate/advanced readers only, the final product has proved to be accessible to readers of all levels despite the advanced nature of the topics.
C++Builder System Requirements C++Builder 5 Developer’s Guide is written, for the most part, for users of C++Builder version 5. Most of the text and example code, however, is applicable to C++Builder version 4 as well. Table I.1 shows the applicability of various versions of C++Builder. TABLE I.1 Percentage of This Book That Is Applicable to Different Versions of C++Builder C++Builder Version
Applicability
C++Builder 5 Enterprise
100%
C++Builder 5 Professional
94%
C++Builder 5 Standard
77%
C++Builder 4 Enterprise
84%
C++Builder 4 Professional
79%
Although most of the code in the book should work with C++Builder version 4 (except version 5 specifics, of course), a lot of the C++Builder project files on the CD-ROM that accompanies this book will be in version 5 format. Because this format is incompatible with C++Builder version 4, it will be necessary for version 4 users to create new projects, insert code from the companion CD-ROM, and add forms and properties as appropriate. Users of C++Builder 5 Standard and C++Builder 5 Professional should disable the Build with runtime packages option on the Packages tab of the Project Options dialog to compile the example C++Builder project files included on the CD-ROM.
3
01 9721 intro
4
4.19.01
8:44 AM
Page 4
C++BUILDER 5 DEVELOPER’S GUIDE
The minimum system requirements for C++Builder 5 Enterprise are as follows: • Intel Pentium 90 or higher (P166 recommended) • Microsoft Windows 2000, Windows 95, 98, or NT4.0 with Service Pack 3 or later • 32MB RAM (64MB recommended) • Hard disk space: 253MB for compact install, 388MB for full install • CD-ROM drive • VGA or higher resolution monitor • Mouse or other pointing device
How This Book Is Organized This book is organized into seven parts. The first five parts have been arranged with natural progression in mind. These cover topics ranging from C++Builder and C++ techniques through communications, database, Web and distributed programming, to advanced, more general programming topics such as OpenGL programming and software installation/distribution. The last two parts contain C++Builder hints, tips, how-tos, an example real-world application, and other recommended sources of C++Builder information. The parts of the book are as follows: • Part I: “C++Builder 5 Essentials”—This part, consisting of Chapters 1–11, contains everything you need to know to make the best use of C++Builder 5 when developing applications. This includes an introduction to C++Builder and the Integrated Development Environment (Chapters 1 and 2); advice on C++ programming and software development with C++Builder (Chapters 3–5); compiling, optimizing, and debugging considerations (Chapters 6 and 7); and comprehensive information on using and writing VCL components (Chapters 8–11). • Part II: “Communications, Database, and Web Programming”—This part, consisting of Chapters 12–14, covers many aspects of communications, database, and Web programming. This includes serial communications and Internet protocols (Chapter 12); WebBroker, InternetExpress, and XML programming (Chapter 13); and database programming, particularly ADO Express, InterBase Express, the new Data Module Designer, and a discussion of database architecture options (Chapter 14). • Part III: “Interfaces and Distributed Computing”—This part, consisting of Chapters 15–22, provides detailed information on all aspects of interfaces and distributed computing. This includes using and writing DLLs, C++Builder packages, and plug-ins (Chapter 15); COM, DCOM, and COM+ programming (Chapters 16–18); MIDAS 3 (Chapter 19); CORBA (Chapter 20); integration with Microsoft Office, particularly Word and Excel (Chapter 21); and ActiveX programming (Chapter 22).
01 9721 intro
4.19.01
8:44 AM
Page 5
INTRODUCTION
• Part IV: “Advanced Topics”—This part, consisting of Chapters 23–26, covers advanced topics generally not found in C++Builder reference books. These include advanced printing and data presentation techniques (Chapter 23); a comprehensive look at the use of the Win32 API (Chapter 24); image processing, graphics (GDI, GIFs, JPEGs, and so on), and sound (WAV, MP3, and so on) with C++Builder (Chapter 25); and a look at advanced graphics programming with DirectX and OpenGL (Chapter 26). • Part V: “C++Builder Application Deployment”—This part, consisting of Chapters 27–29, contains more information not generally found in C++Builder books. This includes techniques and advice for creating standard Windows and HTML help files (Chapter 27); software distribution considerations, with a particular emphasis on shareware (Chapter 28); and techniques for software installation and updates, including version control with TeamSource (Chapter 29). • Part VI: “Knowledge Base”—This part, Chapters 30 and 31, contains a set of C++Builder hints, tips, and how-tos (Chapter 30); and an example real-world application (Chapter 31). • Part VII: “Appendix”—This appendix contains a comprehensive list of C++Builder resources, including Web sites (especially the Borland community Web site and CodeCentral), newsgroups, discussion lists, forums, books, magazines, and user groups.
Conventions Used in This Book This section describes the important typographic terminology and command conventions used in this book. Features in this book include the following:
NOTE Notes give you comments and asides about the topic at hand, as well as full explanations of certain topics.
TIP Tips provide great shortcuts and hints on how to use C++Builder 5 more effectively.
5
01 9721 intro
6
4.19.01
8:44 AM
Page 6
C++BUILDER 5 DEVELOPER’S GUIDE
CAUTION These warn you against making your life miserable and tell you how to avoid the pitfalls in programming.
In addition, you’ll find various typographic conventions throughout this book: • Commands, variables, directories, and files appear in text in a special monospaced
font.
• Placeholders in syntax descriptions appear in a monospaced italic typeface. This indicates that you will replace the placeholder with the actual filename, parameter, or other element that it represents.
02 Part 1
4.6.01
1:59 PM
Page 7
PART
C++Builder 5 Essentials
I
IN THIS PART 1 Introduction to C++Builder
9
2 C++Builder Projects and More on the IDE 3 Programming in C++Builder
53
95
4 Advanced Programming with C++Builder 5 User Interface Principles and Techniques
147 225
6 Compiling and Optimizing Your Application 7 Debugging Your Application 8 Using VCL Components
335
389
437
9 Creating Custom Components
499
10 Creating Property and Component Editors 11 More Custom Component Techniques
701
577
02 Part 1
4.6.01
1:59 PM
Page 8
03 9721 CH01
4.6.01
1:59 PM
Page 9
Introduction to C++Builder Chris Winters Khalid Almannai Jarrod Hollingworth Vikash Shah
IN THIS CHAPTER • C++Builder Basics • What’s New in C++Builder 5 • Upgrading and Compatibility Issues • Migration from Delphi • Advantages and Disadvantages of C++Builder 5 • Preparation for Kylix
CHAPTER
1
03 9721 CH01
10
4.6.01
1:59 PM
Page 10
C++Builder 5 Essentials PART I
Throughout this chapter we will introduce you to Borland C++Builder, one of the leading development environments for creating Internet, desktop, client/server, and distributed applications. It combines the ease of a RAD environment with the power and performance of ANSI C++. C++Builder is the tool of choice for hobbyist programmers, development teams in small and medium-size companies, and large teams in major corporations alike.
NOTE For more information on the features and benefits of C++Builder, see the “Features & Benefits” and “New C++Builder Users” links on the C++Builder Web site at http://www.borland.com/bcppbuilder/.
Seasoned C++Builder 5 programmers might choose to skip this chapter. For the rest of you, we will show the basics of C++Builder, migrating to C++Builder from other development environments, the advantages and disadvantages of C++Builder in comparison with other development environments, and an overview of what’s new in version 5 of C++Builder. On a slightly different note, we introduce you to Kylix, the code name for Borland’s upcoming development environment for the Linux operating system, one of the most anticipated development products in recent years. Kylix is basically C++Builder and Delphi for Linux, allowing you to create Linux applications as easily as you can create Windows applications with C++Builder and Delphi. Most of what you have learned and will learn with C++Builder and much of your existing code can be applied to Kylix.
C++Builder Basics In this section we will describe the basics of C++Builder and develop a simple application. By reading over the basics, you will see that C++Builder is quite easy to use.
Hello World! A Basic Start You just opened up your copy of C++Builder, threw the manuals aside, installed it, and are ready to go—right? We will go through the basics of C++Builder, projects, the VCL (Visual Component Library), Object Inspector, and more. If you are a beginner and need to learn really quickly, this chapter is for you! If you are an advanced developer and you are ready to burn more knowledge into your head, skip this chapter and move on to the real meat-and-potatoes. Developers used to do command-line programming using great products such as Turbo C++. Since Windows dominated the operating system market, compilers moved very quickly toward
03 9721 CH01
4.6.01
1:59 PM
Page 11
Introduction to C++Builder CHAPTER 1
With the introduction of OWL (ObjectWindows Library), things started getting easier. OWL contained all the programming headaches and made it easier to develop applications. The Borland C++ 3.1 compiler contained OWL, and Windows development started getting a little easier. After some time, Borland introduced Borland 5.0 compiler, which OWL and the IDE improved. Shortly after the success of Borland C++ 5.0, Delphi appeared on the market. Delphi was the visual Pascal language. Soon after the release, Borland released C++Builder, which was developed from Delphi. C++Builder used the same technology and from that point, Windows development became a lot easier than before. Delphi contained advanced RAD (Rapid Application Development) technologies, and C++Builder inherited this technology and became one of the best compilers in the world today. Compared to Visual C++, developing applications is faster and can be easily ported to other platforms. For the end user and the future developer, C++Builder has become one of the most popular compilers in the world. It is easy to use, and you can quickly learn how to navigate. Visual Basic developers will see that Visual Basic’s component manipulation is similar to C++Builder’s. Also, the IDE is somewhat similar and easy to navigate around. You do have to learn C++, which takes several years to master. However, Borland C++Builder can aid in that learning. Borland/Inprise has made it easy—the VCL and its class functions do the hard work for you. If you want to move to the fast-paced world of RAD development, C++Builder is the way to go. OK, let’s get started. First, consult your manuals and make sure C++Builder is installed properly on your system. Then, go ahead and start it up.
NOTE I will not go into great detail about each part of C++Builder, because that’s a whole book in itself! Plus, you can access the manuals or online help for installation and operation. What I will do is explain some basics to get you started building simple applications.
1 INTRODUCTION TO C++BUILDER
Windows programming. When Borland introduced Borland C++ Compiler 3.1, the world started moving into Windows development. However, it was still hard to grasp, and you still had to do all the hard work. Sometimes it would take three to five pages just to display a window, because of all the code to catch the messages to manipulate the window, draw the window, and perform other techniques within the Windows environment.
11
03 9721 CH01
12
4.6.01
1:59 PM
Page 12
C++Builder 5 Essentials PART I
When C++Builder has fully loaded, you will see the three main windows for the programming environment. This is called the Integrated Development Environment (IDE). The IDE has everything you need in one place, as you can see in Figure 1.1. The IDE is the programming work area for your project. Here you will manipulate controls or components, type in code, configure C++Builder, and maybe set properties of the project. Speedbar
Object Inspector
Main Menu
Component Palette
Form
Code Editor
FIGURE 1.1 The C++Builder IDE.
The VCL, Forms, and Components The Visual Component Library (VCL) is a repository of the components used to create C++Builder applications. A component is an object you use to make up the program, such as a check box, a drive combo box, or a graphical image. These components are chosen by leftclicking and placing them in your work area. VCL components are code that is compiled to perform certain operations, eliminating even more code that you might have to type. You can also add or write your own components, which is discussed in upcoming chapters. The components that make up the VCL remove most of the hard work for you. These components are located in the Component Palette. See the section “The Component Palette,” later in this chapter.
03 9721 CH01
4.6.01
1:59 PM
Page 13
Introduction to C++Builder CHAPTER 1
The Object Inspector also has an Events tab, where you can create events to indicate user interaction with the component. These events perform other actions that you define.
The Form A form is a visible window that is, in most instances, the user interface of your application. When you create a new application in C++Builder, a blank form is created automatically. To build the user interface you simply add visual components to the form, then position and size them accordingly. You can also add non-visual components to a form, such as timers. These appear as a simple component icon at designtime but are not visible at runtime. By default, when a user runs your application the form will be displayed in the center of the screen. You can alter the initial position of the form and other settings by changing the form properties in the Object Inspector.
The Speedbar The Speedbar provides quick access to the menu functions most commonly used within C++Builder, such as Run, Step Through, View Unit, View Form, and Add to Project. You can customize the Speedbar to your liking by adding the functions you prefer and removing those you don’t use. Customizing the IDE Toolbars One of the main features of the IDE is its capability to be customized. You can add or remove any speed button to or from any toolbar except for the Component Palette, which contains components, not commands. The C++Builder toolbars are as follows: • Standard • View • Debug • Custom • Component Palette To customize a C++Builder toolbar, follow these steps: 1. Right-click anywhere on the toolbar. 2. Choose Customize.
1 INTRODUCTION TO C++BUILDER
All components have properties, which can be manipulated by code or C++Builder. A component’s properties determine how it performs, how it looks, what functionalities it has, and so forth. You can modify the properties of a component with the Object Inspector, which is the panel at the left of the screen under the main menu when the Properties tab is selected (refer to Figure 1.1). You can also change property settings in code, but I would not recommend that unless you get really familiar with C++Builder and the VCL.
13
03 9721 CH01
14
4.6.01
1:59 PM
Page 14
C++Builder 5 Essentials PART I
3. The Toolbars Customize dialog will be displayed, as shown in Figure 1.2. 4. Click on the Commands page. 5. Now you can drag and drop any command you want to the toolbar. 6. To remove any speed button from the toolbar, just drag it outside the toolbar.
FIGURE 1.2 The Toolbars Customize dialog.
The Component Palette The Component Palette, located under the main menu, is an inventory of all the components in the VCL. These components are grouped by categories, the names of which are displayed on the tabs above the components. To pick a component, click it with your left mouse button, then click again on the form to place the component where you want it. As indicated previously, you can modify the component’s properties with the Object Inspector or by changing the code.
Events and Event Handlers In your first lesson in learning C++Builder, we will place a simple button on the form, set an event for the button, and run the program. You see buttons on almost every Windows application. It is a simple object that enables a user to trigger an event. The Button component is located under the Standard tab of the Component Palette. Its icon looks like a standard button with OK in the middle. To place a Button component on the form, left-click the icon one time; then, left-click again on the center of the form. Figure 1.3 shows the form with the button. Voila! You now have placed a button on the form, and C++Builder has created an instance of that button within the code. At the moment the button isn’t very useful because it doesn’t do anything. If you were to compile and run the application nothing would happen when you click on the button. Typically though, when a user presses the button you want to perform some
03 9721 CH01
4.6.01
1:59 PM
Page 15
Introduction to C++Builder CHAPTER 1
FIGURE 1.3 A Button component added to the form.
When the button is clicked at runtime, an event is generated. For your application to respond to this event you need to create an event handler. An event handler is simply a function that is automatically called when its event occurs. C++Builder creates the outline for the OnClick event handler, the event that occurs when the user clicks the button, when you double-click on the Button component at designtime. You can do the same thing by selecting the Button and then double-clicking in the OnClick field on the Events tab in the Object Inspector. Once the outline for the event handler is created, you can then add code to perform the necessary action that should occur when the button is clicked. The outline for the OnClick event handler is shown in the following code. void __fastcall TForm1::Button1Click(TObject *Sender) { }
If you right-click with the mouse in the Code Editor and choose Open Source/Header File, you will see the following code: //-------------------------------------------------------------------------#ifndef Unit1 #define Unit1 //-------------------------------------------------------------------------#include
#include #include <StdCtrls.hpp> #include //-------------------------------------------------------------------------class TForm1 : public TForm
1 INTRODUCTION TO C++BUILDER
action, such as saving information that the user may have entered, displaying a message to the user, and so on.
15
03 9721 CH01
16
4.6.01
1:59 PM
Page 16
C++Builder 5 Essentials PART I { __published: // IDE-managed Components TButton *Button1; void __fastcall Button1Click(TObject *Sender); private: // User declarations public: // User declarations __fastcall TForm1(TComponent* Owner); }; //-------------------------------------------------------------------------extern PACKAGE TForm1 *Form1; //-------------------------------------------------------------------------#endif
This code is generated automatically within C++Builder. I put it here for clarity to show you what C++Builder can do for you automatically. Now we’ll add code to display a message when the button is clicked, that the program is going to end, and then we’ll terminate the program. In the code editor, click on Unit1.cpp to move back to the Button component’s event. Type the following code inside the event that you just created: void __fastcall TForm1::Button1Click(TObject *Sender) { ShowMessage(“Hello world! This is a test application! Press OK”); Close(); }
This code can probably be understood even by a beginner. When the program runs, the user clicks on the button and an event is triggered. Our OnClick event handler will display a dialog box with our friendly message. When the user closes the dialog box our program then terminates due to the Close() method that we called.
Let’s Run It and See! From the Speedbar, click the green arrow that looks like the Play button of a tape player. On the main menu, click Run and choose Run. (As a shortcut, you could press F9 instead.) When you press the Run button, C++Builder will start to compile and execute the program. It then waits until you press the button. When you do so, the dialog appears revealing the message. The program exits when you press OK. After viewing your program, let’s close out our current project. From the main menu, choose File, New Application. C++Builder will ask if you want to save the application project; answer No. Let’s write a real program that can do something.
03 9721 CH01
4.6.01
1:59 PM
Page 17
Introduction to C++Builder CHAPTER 1
17
Your First Real Program
1
Choose File, New Application from the main menu. C++Builder will create a new project and generate code to create an empty form. Now we’re ready to create an application with as little code as possible.
INTRODUCTION TO C++BUILDER
On the Component Palette, select the Additional tab and then the Image component. If you aren’t sure, its icon has the sky, a hill, and water at the foot of the hill. If you put your mouse over each icon, a helper will tell you what it is. After selecting the Image component by clicking it, move your mouse to the form and click one time to place the component on the form. You will not see much, but a square outline will appear. This component displays graphical images. Under the Properties tab in the Object Inspector, go to the stretch attribute and select True. From the Component Palette, go to the Dialogs tab and choose the OpenDialog component. If necessary, scroll through the Component Palette with the left and right arrows. The OpenDialog component looks like an open yellow folder. Select it with your left mouse button and place it anywhere in the top right corner of the form. The component now is part of your form and is used for displaying a dialog box in which you can choose files. It can also open the files that you pick. Now we want to set an attribute to this component. Go to the Object Inspector and look for the attribute named Filter, located under the Properties tab. Enter the following text into the edit box for that attribute: BMP files|*.bmp
From the Standard tab of the Component Palette, select two Button components. Instead of placing one Button component at a time, you can place multiple Button components by holding down the Shift key and pressing the Button icon from the Component Palette. Click on the form and a Button component appears. Click on the form again and another Button component appears. Now select the white arrow on the left side of the Component Palette. This is the Object Selector in which you can navigate and select your components or objects on your form. Because we are done placing buttons, we now want to be able to select other components. Click one time on the Button1 component on the form. This selects the button itself. We now want to modify the attributes of that particular component. In the Object Inspector, click inside the Caption attribute and replace the existing text with the words Get Picture. The Caption attribute is where the button displays information to the user. Delete the existing text if needed. This gives your button a new caption to users.
03 9721 CH01
18
4.6.01
1:59 PM
Page 18
C++Builder 5 Essentials PART I
Go to the Win32 tab in the Component Palette and select the status bar. It looks like a gray bar with a grip. Hold your mouse over the components a couple of seconds to find the component named StatusBar. A status bar is usually located at the bottom of most Windows applications and displays the status of an application. Place this on the form. You will see that the component falls to the bottom of the form. Now double-click on the Button component on the form (Object Inspector will display Button1) to set an event. Enter the following code: void __fastcall TForm1::Button1Click(TObject *Sender) { if(OpenDialog1->Execute()) Image1->Picture->LoadFromFile(OpenDialog1->FileName); StatusBar1->SimpleText = OpenDialog1->FileName; }
Let’s pause to explain what’s going on. The window you now see is the Source Code window. It can always be accessed by the Project Manager or by the Object Inspector. The Source Code Edit window is where you will type in source code for your program. Now let’s set focus on our form. To access our form, we can use the Speedbar tool button named Toggle Form/Unit. It looks like a form and a piece of paper with arrows pointing toward the form on both sides. If you hold your cursor over this button, it will display Toggle Form/Unit (F12). Another way to toggle between forms and code is with the F12 key. Press F12 now to set focus on the form. Click one time on Button2 (Object Inspector will display Button2) on the form and set the caption to Close. Double-click on that button and enter the following code: void __fastcall TForm1::Button2Click(TObject *Sender) { Close(); }
Now focus on your form again by moving the source code editor out of the way and clicking on your form. Doesn’t look like much, does it? Soon you will see how much C++Builder has done for you with a little bit of code! Before running this application, arrange your buttons and other components nicely to give a clean look. Use the white arrow selector on the left side of the Component Palette to select any component. You will not be able to move the StatusBar component at the bottom of the form, so you can skip that one. Press the green Run arrow, or choose Run, Run from the main menu. C++Builder should compile the program if you did not have any typos. Your program should appear with two buttons with the captions Get Picture and Close. Choose the Get Picture button.
03 9721 CH01
4.6.01
1:59 PM
Page 19
Introduction to C++Builder CHAPTER 1
After selecting the file, press OK. You should see a picture of the Windows Setup bitmap. At the bottom of the form, the name of the file will be in the status bar. You have written your first application that really works, and with as little code as possible! Let’s explain what really happened, so that you can get a feel for the components. First you placed an Image component on the form. This component enables you to display .BMP files within your program. With this component, C++Builder takes all the grunt work out for you. If you wanted to display a graphic file in Windows, you would first need pages and pages of code just to load the palette of colors the BMP has. You would also have to perform error checking against the BMP structure it fills in, error check to make sure it’s a .BMP file, set the resolution, and much more, just to display the picture itself. C++Builder has already done this for you. All you have to do is drop the component on the form and set its properties. You then set the stretch property, which stretches the picture to match the size of the component you placed on the form. For larger pictures, resize the component using your mouse. After dropping the Image component on the form, you also placed an OpenDialog box. The OpenDialog component lets the user select a file to open under a directory. In this case, we used the OpenDialog component to select the filename of the image to open. The Image component determines if it is a graphic file, reads it in, and displays its contents. We set the Filter property on this component to find all files that end in the .BMP extension, which describes the file type we are opening. It will also display this file type in the OpenDialog box as the type to open. The | is a separator to tell C++Builder there’s another parameter coming for this type of property. *.BMP tells the OpenDialog box to open only files that end in .BMP. If you want to see how this looks or change the filter settings during designtime, go to Form1 and select the OpenDialog component by clicking it. Then go to the Object Inspector. In the Filter section, double-click within the text area and a table will come up that displays what I just described. After that you placed two Button components. We also set the captions of the Button components, which identifies what the buttons do. Then we set events for the Button components. You can also set other events with the Object Inspector. The Object Inspector has an Events tab that lists the events a component has. To set off a particular event, simply double-click in the text area of that event. If you were to write this whole program using barebones code, you would produce at least 20 pages of code. The idea of this chapter is to show you the basics and to demonstrate how quickly you can use C++Builder.
1 INTRODUCTION TO C++BUILDER
An Open dialog box will appear asking for a file with the .BMP extension. Go to your Windows directory under your C: drive and select SETUP.BMP or another file that has a .BMP extension.
19
03 9721 CH01
20
4.6.01
1:59 PM
Page 20
C++Builder 5 Essentials PART I
Let’s write another program using different components. This will give another example of RAD technology within C++Builder.
NOTE Go ahead and close the project. You do not have to save it. Choose File, Close All from the main menu and answer No.
From the main menu, select File, New Application. A new project will be created. Let’s save this project by selecting File, Save Project As from the main menu. Give the form’s source code a name. Change the default Unit1.cpp to Mainfrm.cpp. After saving the form’s source code, the project source code will appear. By default, it is Name it Proj.bpr.
Project1.pbr.
Place two ListBox components on the form. The list boxes are in the Standard tab in the Component Palette. Don’t worry about placing them in a specified location, but do align them next to each other. C++Builder creates them as ListBox1 and ListBox2. Drop an EditBox and two Buttons below the list boxes. They are also located in the Standard tab in the Component Palette. Align them any way you want. C++Builder creates the buttons as Button1 and Button2. It also creates an Editbox named Edit1. Select Button1. In the Object Inspector, select the Caption property. Change the caption to ADD. Select Button2. In the Object Inspector, select the Caption property. Change the caption to REMOVE. Select Edit1. In the Object Inspector, select the Text property. Remove the string within the Text property. Drop a Label component under the Edit1 edit box. In the Object Inspector, select the Caption property. Enter Friends’ Names. To select the form itself, click anywhere on the form, but not on any component. You can also do this inside the Object Inspector by selecting Form1 in the drop-down box. Select the Events tab in the Object Inspector and look for the OnCreate event. Double-click inside the property setting for this event. C++Builder will now create the following code for the event handler: void __fastcall TForm1::FormCreate(TObject *Sender) { }
03 9721 CH01
4.6.01
1:59 PM
Page 21
Introduction to C++Builder CHAPTER 1
void __fastcall TForm1::FormCreate(TObject *Sender) { ListBox1->Items->Add(“David Sexton”); ListBox1->Items->Add(“Randy Kelly”); ListBox1->Items->Add(“John Kirksey”); ListBox1->Items->Add(“Bob Martling”); }
Switch back to the form and double-click on Button1. This is the button with the Add caption. An event will be created. Type the following inside the event handler: void __fastcall TForm1::Button1Click(TObject *Sender) { String GetListItem = ListBox1->Items->Strings[ListBox1->ItemIndex]; ListBox2->Items->Add(GetListItem); }
Switch back to the form, and double-click on Button2. This is the button with the Remove caption. C++Builder will create an event. Type the following inside the event handler: void __fastcall TForm1::Button2Click(TObject *Sender) { ListBox2->Items->Delete(ListBox2->ItemIndex); }
Switch back to the form and select the Edit1 edit box. From the Object Inspector, choose the Events tab. Find the OnKeyPress event. Double-click in the empty area for this event, and the event handler will be created by C++Builder. Type the following code in the event handler: void __fastcall TForm1::Edit1KeyPress(TObject *Sender, char &Key) { if (Key==13) { ListBox2->Items->Add(Edit1->Text); ListBox1->Items->Add(Edit1->Text); } }
Now let’s save the project we are working on. Remember to always save your work! Select File, Save All from the main menu. After saving the project, let’s make the project. Press Ctrl+F9 or choose Project, Make Proj.exe. This will create the executable. If there are any errors, check for typos.
1 INTRODUCTION TO C++BUILDER
You need to place code inside this event. It is triggered when the form is created at runtime. This means that when you run this program, Windows will create the form and execute any code within the event. Type the following inside the event handler:
21
03 9721 CH01
22
4.6.01
1:59 PM
Page 22
C++Builder 5 Essentials PART I
Let’s run it and see what happens. Press the green arrow to run the application we just created. You can also choose Run from the main menu as well. I will explain how the code works in a minute. The application should appear as a regular window with two list boxes with names in them. There should also be two buttons on the form. The edit box (which is our Edit1 component) will have the cursor in it ready for us to type. Enter your friends’ names. As soon as you press Enter, each name will be added not only to the first list box but also to the second list box. Select one of the names and press the Add button. The name you selected will appear in the next list box beside it. If you press Remove, the name will disappear from the second list box only. Select the names and add them to the other list box. Then remove the names. As you see, we added an event for FormCreate. This event executes after the form’s creation. In this event you will see that there are some strings to be added inside ListBox1. The strings are added to the items of the list box. The next event we set is under Button1. We created a string from the String class named which equals the item that was selected by the user. How did this event know that the item was selected? It didn’t. It read the item’s index. If there was no selection, it would be null. The next line adds the string from the index of ListBox1. GetListItem,
Button2’s
event is smaller than the first. It gets the index of the item inside ListBox2 and
deletes it. For our third event, we used an OnKeyPress for the Edit1 edit box. When a user enters data and presses a key, the event is triggered, executing code inside it. This particular event scans for the Enter key, which is equal to 13. Of course, we could have used the VK_ENTER value that C++Builder defines as the Enter key. The if statement checks the passed parameter of Key to see if this is true. If it is, the code inside the if statement executes and adds the string within the edit box to both list boxes. We created three events, and the code is pretty small. We also put several components on the form without any code at all. We have a working program with minimal code. As you can see, you built this application in just a few minutes. Once you get used to the Component Palette, the Object Inspector, and some operations within the IDE, you’ll be on your way to learning the ins and outs of C++Builder. If you compare the time required to develop applications using other compilers, such as Visual C++ or Microsoft Foundation Classes (MFC), you will see that C++Builder is far superior to the others.
03 9721 CH01
4.6.01
1:59 PM
Page 23
Introduction to C++Builder CHAPTER 1
How to Get Around This section gives the answers to some commonly asked questions about the C++Builder compiler. • How do I look at a project’s source code and other source code for each form? You can do this by using the Project Manager and the Project menu item in the main menu. Project, View Source will display the main entry source for the starting application. If you want to view source files from other forms, includes, or resource files, use the Project Manager. To bring up the Project Manager, select View, Project Manager or press Ctrl+Alt+F11. • How do I change properties on a component? You can do this with the Object Inspector. To bring it up, press F11 or choose View, Object Inspector. In the Object Inspector, select your component and the properties will be loaded within the Object Inspector. From there you can set events and change properties. • I am trying to arrange my components precisely, but I am having difficulty. Can I have more control over the alignment? To move a component to the exact location you want, press Control and use the arrow keys to move the component. This will give you the exact pixel alignment you need within C++Builder. • I just compiled and ran my application, but now it seems to be locked up. A bunch of weird windows popped up and I do not know what to do. How can I stop this madness? You can get C++Builder to reset the program. Press Ctrl+F2 or select Run, Program Reset. This will kill your program completely and take away those nasty whatever-theyare-windows, and you’ll be back to your code. • I compiled my first program, but I want to create my own icon and include it in my program. How do I do this? First, use the trusty and wonderful Image Editor. Open it by selecting Tools, Image Editor in the main menu. Simply create a new icon from there and save it. Then, select Project, Options. The Project Options dialog will appear. Select the Application tab and press the Load Icon button. Locate your icon and press OK. Then you will have to rebuild your project. Compiling or making your project will not do it. You will have to rebuild all by choosing Project, Build All Projects from the main menu. After that, your application will contain your new icon!
1 INTRODUCTION TO C++BUILDER
Explore the menu items under C++Builder. The online help will also guide you through the menu items, Object Inspector, and some other options within the IDE.
23
03 9721 CH01
24
4.6.01
1:59 PM
Page 24
C++Builder 5 Essentials PART I
• Every time I compile an application, my form has the name Form1. How do I change this? Remember the Object Inspector? We talked about this for setting properties for components. You can also use it to set properties for your forms. Use the Caption property attribute to change a form’s title. Try experimenting with the Object Inspector for different results! • I am tired of choosing the menu items for something simple. Isn’t there an easier way? Yes—it’s called the Speedbar, and it is located right above the Object Inspector (by default). If you want, for example, to create a new application object, press the button with the image of a white piece of paper. If you do not know what those buttons are, hold your cursor over one for a couple of seconds, and a helper will appear to tell you what the button is. • I have all my components in place and do not want to move them. Sometimes I accidentally move them by mistake. Is there a way I can keep these components still? Yes, you can do this by choosing Edit, Lock Controls from the main menu. This will lock all controls on the form.
What’s New in C++Builder 5 As with the staggered releases of new versions of Borland C++Builder and Borland Delphi in the past, C++Builder 5 introduces new features first seen in Delphi 5 and then adds some more. There are many new features and enhancements in the areas of Web programming, distributed application development, team development, application localization, debugging, database application development, and developer productivity, among others. Most of the new features and enhancements are covered in more detail throughout this book. C++Builder 5 is available in three versions: Standard (Std), Professional (Pro) , and Enterprise (Ent). Standard has the fewest features but is still a powerful development environment for Windows programming and includes over 85 components for RAD programming, the awardwinning compiler, advanced debugger, and more. The Professional version has over 150 components and adds features including the new CodeGuard™ tool, multiprocess debugging, and standard database functionality. The Enterprise version has over 200 components, including Internet Express, CORBA development, Microsoft SQL Server 7 and Oracle 8i support, MIDAS development, a full suite of internationalization tools, TeamSource version control manager, and more. Missing from C++Builder 5 is Merant (formerly Intersolv) PVCS Version Control.
03 9721 CH01
4.6.01
1:59 PM
Page 25
Introduction to C++Builder CHAPTER 1
NOTE
You can also see information on the new features in the “What’s New” section of the C++Builder online help.
The features listed in the following sections are available in the Professional and Enterprise versions of C++Builder 5 and not in the Standard version, except where noted. In the remainder of the book, we will not make a distinction of which versions of C++Builder the new features apply to. Consult the full-feature matrix if necessary.
Web Programming Most people know that one of C++Builder’s strengths is in developing Web and Internet applications. In C++Builder 5, Borland has added the Active Server Page (ASP) Application Wizard, Internet Express (Ent), a new Web browser component, and WebBroker enhancements. The new Internet Express (Ent) allows you to build “thin” clients for the Web by presenting data from MIDAS servers and back-end databases using XML and HTML 4. Thin clients are smaller in size than regular (or “fat”) clients. They do not access the database directly and therefore do not require the Borland Database Engine (BDE) to be installed on the client machine. WebBroker is now available in the Professional version of C++Builder 5 (previously Enterprise only) and is now able to preview with HTML 4 support. The last main Web programming addition to C++Builder 5 is the new Web browser component, which allows you to integrate HTML browsing into your applications. This seemingly simple feature can be used in many ways, such as to • Create your own customized Web browser. For instance, develop one for your company that allows users to view Web pages only within the company’s intranet. • Create the user interface for your program in HTML. This has several benefits. The user interface can now be created by nonprogrammers. If there are Web page developers in your organization, they can assist in application development. Additionally, you can dynamically customize the user interface for a particular user’s level of experience simply by loading a different HTML file. The user interface can also be customized for a particular client. Shipping a new version of the user interface is as easy as downloading an HTML file, something that browsers do extremely well.
1 INTRODUCTION TO C++BUILDER
The full-feature matrix highlighting all of the new features in each version (Standard, Professional, Enterprise) of C++Builder 5 is available from the “Feature List” link on the C++Builder Web site at http://www.borland.com/bcppbuilder/.
25
03 9721 CH01
26
4.6.01
1:59 PM
Page 26
C++Builder 5 Essentials PART I
• Integrate your help files using HTML, making the creation of help files as simple as creating Web pages. Several products, such as Microsoft Encarta and Microsoft Office 2000, use a Web browser control in these ways. America Online (AOL) and CompuServe use Web browser controls to create their customized browser applications.
Distributed Applications CORBA (Ent) now supports the VisiBroker ORB v4.00 and CORBA 2.3–compliant clients and servers. Other new CORBA features include the Portable Object Adapter and Objects By Value. There are enhancements to the Visual TypeLibrary Editor, Interface Repository, CORBA Wizards, and more. MIDAS (Ent) now has XML data packet support, a stateless DataBroker, a new Web Connection component, server object pooling, and provider options.
Team Development A great new feature in C++Builder 5 is TeamSource. It is included in the Enterprise version and can be purchased separately for the Professional version. TeamSource is a front-end version control manager that allows parallel development of projects. Developers work on their own local copies of the project. In most cases, TeamSource automatically handles the merging of changes. A visual compare utility simplifies the task of resolving conflicts. TeamSource tracks version history and allows a particular state of the project to be bookmarked. The actual back-end file versioning is performed by separate version control software. C++Builder 5 (Ent) includes the Borland ZLib back-end version control software and also supports an interface to Merant PVCS (purchased separately). Plug-ins can be written for TeamSource to support other back-end version control software.
Application Localization New to C++Builder 5 Enterprise are the Translation Suite, Translation Repository, RC Translator, and DFM Translator. These features can also be purchased separately for C++Builder Professional. They allow you to internationalize or localize your applications for new languages and cultures, simultaneously developing your application for multiple locales. The Resource DLL Wizard has been enhanced to allow you to translate your applications to new languages easily.
03 9721 CH01
4.6.01
1:59 PM
Page 27
Introduction to C++Builder CHAPTER 1
27
Debugging
1
Perhaps one of the best new features that most C++Builder programmers can benefit from is CodeGuard. CodeGuard is a runtime error-detection tool that can locate and diagnose memory and resource leaks. In addition, some other new debugging features are an FPU/MMX View and breakpoint actions (all versions) and groups (all) for programmable breakpoint control and managing multiple breakpoints at once.
INTRODUCTION TO C++BUILDER
Database Application Development There are several new database features in C++Builder 5, including the DataModule Designer, InterBase Express, and ADO Express. The DataModule Designer, first seen in Delphi 5, allows you to see and design the parent-child relationships among data-access components in the tree view and entity relationship dependencies (including master-detail) in the Data Diagram view. With InterBase Express, you can develop high-performance database applications using InterBase that don’t require the Borland Database Engine (BDE). It comes with the new SQL monitor for advanced data access debugging. ADOExpress is a new set of components that allows you to access relational and non-relational databases using Microsoft’s ActiveX Data Object (ADO) and OLEDB technology. Using ADO, you can access standard databases, email, file systems, spreadsheets, and other information. ADOExpress applications don’t require the BDE. In addition to these new features, C++Builder 5 now has InterBase 5.6, MS SQL Server 7, and Oracle 8i support.
Developer Productivity There are some great new features in the area of developer productivity. Multithreaded background compilation (all) allows you to continue working while the compiler is doing its stuff. Custom Desktop Settings (all), with auto-debug mode switching, allows you to arrange and save different IDE desktops just the way you want. You can set a separate layout for debugging applications and, as you switch in and out of debugging, the desktop changes your layout automatically. An integrated to-do list manager lets you add simple task reminders with a comment and priority to your projects. A to-do item can appear in your code as a reminder to come back to something that needs to be finished. There’s a new to-do list view to manage those items. Several wizards have been added, including a Windows 2000 Client Logo Application Wizard (all), Console Application Wizard (all), Control Panel Applet Wizard, and simple C and C++ Application Wizards (all).
03 9721 CH01
28
4.6.01
1:59 PM
Page 28
C++Builder 5 Essentials PART I
There is also enhanced Microsoft Visual C++ support, including Visual C++ 6.0 projects, Microsoft Foundation Class (MFC) 6.0, and Active Template Library (ATL) 3.0 support. There are many more developer-productivity features and enhancements new to C++Builder 5, including per-file project options override (all), property categories (all), and property images (all) in the Object Inspector; programmable code editor key mappings (all); new components (all); and the capability to import automation servers as components.
Companion Tools CD-ROM The C++Builder 5 companion tools CD-ROM (Pro/Ent) contains more than 40 useful thirdparty tools. Some are full versions, and some are shareware and trial versions. Some of the full and free tool highlights are • Debug Server 1.1 from Elitedevelopments is a COM/DCOM-based debugging output manager that lets you centrally collect, manage, and display debug messages from your applications. • Morfit’s 3D Engine SDK 3.0 and WorldBuilder 3.1 allow you to incorporate 3D graphics into your applications and develop arcade-quality games. • GExperts is an open-source product that contains dozens of IDE enhancements to speed development. Several “Experts” are included to navigate, search, and transform your code. GExperts also provides shortcuts for common programming tasks, quick access to information relevant to C++Builder developers, and extensive customizing of the IDE.
Upgrading and Compatibility Issues C++Builder 5 was officially released on March 22, 2000. At the time of the writing of this book, there are several known compatibility problems in C++Builder 5 with existing projects and third-party tools, and there are unresolved bugs. C++Builder 5 Update #1 is available for download from the "Updates and Patches" link on the Borland C++Builder Web site at http://www.borland.com/bcppbuilder/. It fixes many compiler, runtime library, ActiveX, and other bugs. Updates for other versions of C++Builder are also available. The current bug list for all versions of C++Builder can be viewed via the "Investigate Bugs" link also on this page. Sign up for the C++Builder tech alert from the Borland Web site to get the latest information on known issues and update releases. You should also read the README.TXT files in the root folder of the C++Builder installation CD-ROM for known issues at the time of release.
Upgrading C++Builder from an Earlier Version C++Builder 5 can coexist with earlier versions of C++Builder on your machine, but shared applications such as the BDE will be upgraded to the latest version. C++Builder 5 can also coexist with Delphi installations. The same general rules apply.
03 9721 CH01
4.6.01
1:59 PM
Page 29
Introduction to C++Builder CHAPTER 1
Using Existing Projects in C++Builder 5 When you load a project created in a previous version of C++Builder, the project is automatically converted to work with C++Builder 5. The project file is updated to XML format, and the earlier VCL library versions listed in it are updated to list C++Builder 5 libraries. Some slight changes to the USE* clauses in the main project file source are also made. You may have written version-specific code into your projects or used third-party components that do. Changes to properties and methods in the VCL between different C++Builder versions have typically necessitated the use of #ifdef VERXXX clauses to compile the correct usage. If any of the version-specific code is testing explicitly for C++Builder 4 or earlier versions without a “catch-all” for forward compatibility, you may need to update the clauses. For example, if the code tested #ifdef VER125 for C++Builder 4–specific code, you will need to add either an #ifdef VER130/#endif or an #else catch-all to specify the C++Builder 5–specific code. If you don’t have the source code, usually because it is a third-party component or package, then you will need to contact the vendor to get an update.
Creating Projects Compatible with Previous Versions of C++Builder If you need to create projects that can be used with earlier versions of C++Builder, there are several areas in which care must be taken. In particular, you cannot use new features in forms and project source code, such as new properties, methods, or events. There are several new project, compiler, and linker options that should not be used. The help file contains detailed information on the new features added to C++Builder 5. In C++Builder 5, form files are stored as text rather than binary as in previous versions. To save a form as binary, right-click on the form and uncheck Text DFM. If you want all forms created in the future to be saved as binary, uncheck the New Forms as Text option on the Preferences page of Tools, Environment Options. As shown in detail in Chapter 2, “C++Builder Projects and More on the IDE,” project files are now saved in XML format. The project file in previous versions of C++Builder used a makefile format. You can export a makefile format project file by using the Project, Export Makefile option. You will need to rename the makefile with a .bpr extension and make several changes
1 INTRODUCTION TO C++BUILDER
If you have no use for the previous version of C++Builder, then you should uninstall the previous version before installing C++Builder 5. You should also read the INSTALL.TXT and README.TXT files in the root folder of the installation CD-ROM for further installation and upgrading notes.
29
03 9721 CH01
30
4.6.01
1:59 PM
Page 30
C++Builder 5 Essentials PART I
to the options listed in the file, including the C++Builder version number, set in the VERSION option, and VCL file versions listed in the LIBRARIES, SPARELIBS, PACKAGES, and CFLAG1 options. Converting the project file to previous versions is a bit involved; there are other changes that may be necessary. The to-do list is a new feature in C++Builder 5. However, the in-source to-do list items and global project to-do file require no changes for support in previous versions. If you see the message Error reading symbol file when opening a C++Builder 4 project, you should rebuild the application. C++Builder 4 symbol files are not compatible with C++Builder 5.
Solving Other Project Upgrading Issues There are several new method parameters, data values, classes, and VCL behaviors in C++Builder 5 that you should be aware of. Some of the main changes are listed here. •
TPoint is no longer a structure. The initialization syntax has changed from using braces ({ and }) to formally typecasting two coordinates as a TPoint. See “TPoint, compatibility issues” in the online help.
•
TPropertyEditor
•
TComponentList
•
The sprintf() method of the AnsiString class now overwrites the current contents of the string rather than append to the existing string. A new cat_sprintf() method provides the old behavior.
•
TCppWebBrowser
TPoint
The parameter list for the TPropertyEditor constructor has changed to TPropertyEditor(const di_IFormDesigner ADesigner, int AropCount).
There is a new class named TComponentList to store and maintain a list of components. It is defined in the include file cntnrs.hpp. See the online help for information on how to use TComponentList.
AnsiString sprintf
and THTML The TCppWebBrowser component on the Internet page replaces the THTML component from Netmasters. See the online help for upgrading notes.
• MIDAS Several changes have been made to MIDAS. See the online help for additional information. There are many more upgrading issues in C++Builder 5. The “Upgrading to Borland C++Builder 5” book on the Contents tab of the online help contains detailed information.
Migration from Delphi This section is not to teach you C++, but to get you started with programming in C++Builder, if you know how to program in Delphi. The first thing you should note when programming in C++Builder is that it is case sensitive. It may look like a hard thing to do if you have been programming in Delphi for a long time, but you will get used to it.
03 9721 CH01
4.6.01
1:59 PM
Page 31
Introduction to C++Builder CHAPTER 1
1
CAUTION
Here we will compare Delphi and C++Builder in the major programming areas. At the end of this discussion, you should be able to translate most of your Delphi code to C++Builder without any trouble.
Comments The first thing you need to know is how to enter comments in C++Builder. Table 1.1 compares Delphi to the C++Builder way of creating comments. Delphi-to-C++Builder Comments Comparison
Delphi
C++Builder
{ My comments in Delphi }
/* My comments in C++Builder */
(* Another comment in Delphi *) // One line of comments
// One line of comments
Variables As in Delphi, in C++Builder you must declare the variable type before you can use it. Table 1.2 compares Delphi variables with those of C++Builder. The table also shows the number of bytes that each type requires. TABLE 1.2
Delphi-to-C++Builder Variables Comparison
Type
Size (bytes)
Delphi
C++Builder
Signed integer
1 2 4 8
ShortInt
char
SmallInt
short, short int
Integer, LongInt
int, long
Int64
__int64
INTRODUCTION TO C++BUILDER
Unlike Delphi, the code in C++ is case sensitive.
TABLE 1.1
31
03 9721 CH01
32
4.6.01
1:59 PM
Page 32
C++Builder 5 Essentials PART I
TABLE 1.2
Continued
Type
Size (bytes)
Delphi
C++Builder
Unsigned integer
1 2 4
Byte
BYTE, unsigned short
Floating point
Variant
Word
unsigned short
Cardinal, LongWord
unsigned long
4 8
Single
float
Double
double
10 16
Extended
long double
Variant,
Variant,
OleVariant,
OleVariant, VARIANT
TVarData
Character Dynamic string Null-terminated string Null-terminated wide string Dynamic 2-byte string Pointer Boolean
1 2 -
Char
char
WideChar
WCHAR
AnsiString
AnsiString
PChar
char *
-
PWideChar
LPCWSTR
-
WideString
WideString
8 1
Pointer
Void *
Boolean
bool
The table covers most variables. For more information, refer to the C++Builder help.
Constants There are two ways to declare a constant in C++Builder. The old way is to use the preprocessor directive #define like this: #define myconstant
100
The new and safer way of defining constants is by using the const keyword, as follows: const int myconstant = 100; myconstant
is again declared as a constant, but this time it’s declared as an integer.
03 9721 CH01
4.6.01
1:59 PM
Page 33
Introduction to C++Builder CHAPTER 1
Operators
1
Delphi-to-C++Builder Assignment Operators Comparison
Operator
Operator Type
Delphi
C++Builder
Assignment
Assign Add then Assign Subtract then Assign Multiply then Assign Divide then Assign Modulus then Assign Bitwise And then Assign Bitwise Or then Assign Bitwise Xor then Assign Bitwise Shl then Assign Bitwise Shr then Assign Equal Not equal Greater than Greater than or equal to Less than Less than or equal to Add Subtract Multiply Divide float values Divide integer values Modulus And Or Not
:= None None None None None None None None None None = <> > >= < <= + * / div mod and or not
= += -= *= /= %= &= |= ^= <<= >>= == != > >= < <= + * / / % && || !
Comparison
Arithmetic
Logical
INTRODUCTION TO C++BUILDER
This section explains C++Builder operators, and how you can convert Delphi operators to C++Builder. Table 1.3 lists operators types in Delphi and their counterparts in C++Builder. TABLE 1.3
33
03 9721 CH01
34
4.6.01
1:59 PM
Page 34
C++Builder 5 Essentials PART I
TABLE 1.3
Continued
Operator
Operator Type
Delphi
C++Builder
Bitwise
and or xor not Shift to the left Shift to the right Deceleration Dereferencing Address of variable References Class declaration Structure declaration Scope resolution Direct access Indirect access Increment Decrement
And Or Xor Not Shl Shr ^Type pointer^ @Variable var class record . . None Inc() Dec()
& | ^ ~ << >> Type* *Pointer &Variable Type& class struct :: . -> ++ --
String quoting
‘
“
Pointers
Class
Others
Assignment Operators In C++ you can combine different operators with the assign operator (+=). For example, the following x = x + 2;
can be written as follows: x += 2;
Increment and Decrement Operators In C++ you can increment or decrement variables using prefix or postfix methods. The following is an example of how to use both: x = ++y; // prefix x = y++; // postfix
03 9721 CH01
4.6.01
1:59 PM
Page 35
Introduction to C++Builder CHAPTER 1
int x=5, y=5; x = ++y; // at this point x=y=6 // … later on x = y++; // now x=6 and y=7
Conditional Operators The conditional operator (?:) is the only operator in C++ that takes three expressions and returns a value. It is written as follows: (expression1) ? (expression2) = (expression3)
The operator returns expression2 as a value when expression1 is true. Otherwise it returns expression3. For example return ((a >b)? c : d);
This can be written using an if-else statement as follows: if (a>b) return (c); else return (d);
Pointer Operators The indirection (*) operator is used to declare pointers. The same symbol is also used to dereference a pointer, and in this case it’s called a dereference operator. Dereferencing a pointer is the way to retrieve the value it is pointing to. The compiler is clever enough to tell the difference. Look at the following example: int x, y = 8; int* ptr = &y; // ptr declared and initialized to hold the address of y x = *ptr; // dereferencing ptr.
Here is how you used to do the same thing in Delphi: var x,y : Integer; ptr : ^Integer; begin y:=8; ptr := @y; x := ptr^; end;
1 INTRODUCTION TO C++BUILDER
The first statement tells the compiler to increment y first, then assign x to the new incremented value of y. The second statement is the opposite. It first assigns x to y then increments y. The following example should clarify:
35
03 9721 CH01
36
4.6.01
1:59 PM
Page 36
C++Builder 5 Essentials PART I
The (*) and (&) operators in C++ are equivalent to the (^) and (@) operators in Delphi, respectively. The (&) is called the address-of operator; it is used to retrieve the address of a variable in memory. The (&) operator is also used to declare references. A reference is just a special case of a pointer, and you can treat it as a regular object. References are very useful when used to pass parameters to functions. In Delphi, parameters passed by reference are also called variable parameters. In this case, the (&) reference operator in C++ is equivalent to the var keyword in Delphi.
The new and delete Operators You can always declare variables like this: char buffer[255];
is now allocated on the stack, and this type of variable is called a local variable. There are two problems with local variables. First, they are destroyed when the function returns. Second, the memory size that can be allocated on the stack is limited.
buffer
You can solve these problems by allocating memory from the heap, as follows: char* buffer; buffer = new char;
Or you can write it in one line, such as char* buffer = new char;
Now you have a variable that can be used everywhere in your program with the size you want. The only thing you need to remember is that any memory allocated needs to be freed. This is done with the delete operator, as follows: delete buffer;
Class Operators There are two ways to access data members and member functions of a class, by using direct or indirect access. See the “Classes” section, later in this chapter, for more detail.
Controlling Program Flow As in Delphi, C++Builder has several structures for conditional branching and looping. These structures are •
if-else
•
switch
statements
statements
03 9721 CH01
4.6.01
1:59 PM
Page 37
Introduction to C++Builder CHAPTER 1 for
loops
•
while
1
and do-while loops
C++Builder also has break and continue commands, which are quite similar to the ones in Delphi to break or continue the flow of execution. Table 1.4 shows examples of how to use conditional branching and looping structures in Delphi and their counterparts in C++Builder. TABLE 1.4 Statement if-else
switch
for
Delphi-to-C++Builder Conditional and Loop Statement Comparison
Delphi
C++Builder
if (i = val) then
if (i == val)
begin statement1; ...; end;
{ statement1; ...;}
if (i = val1) then
if (i == val1)
begin statement1; ...; end
{ statement1; ...;}
else if (i = val2) then
else if (i == val2)
begin statement1; ...; end
{ statement1; ...;}
else
else
begin statement1; ...; end;
{ statement1; ...;}
case <Expression> of
switch (<Expression>){
val1 :
case Val1:
statement;
statement; break;
val2 :
case Val2:
statement;
statement; break;
…
…
else statement;
default : statement;
end;
} // end switch
// end case
for i := val1 to val2
do
for(i=val1;i<=val2;i+=inc)
begin statement1; ...; end;
{ statement1; ...;}
// Increment by 1 only.
// Increment by any value // depends on inc value.
for i:=val1 downto val2 do
for(i=val1;i>=val2;i-=dec)
begin statement1; ...; end;
{ statement1; ...;}
// Decrement by 1 only.
// Decrement by any value // depends on dec value.
INTRODUCTION TO C++BUILDER
•
37
03 9721 CH01
38
4.6.01
1:59 PM
Page 38
C++Builder 5 Essentials PART I
TABLE 1.4
Continued
Statement
Delphi
C++Builder
while
while i = val do
while (i == val)
begin statement1; ...; end;
{ statement1; ...; }
repeat
do
statement1;
{
… …
statement1;
…
until (i = val)
} while
do-while
(i != val);
The following are some tips on how to use these statements and commands: • You need to place a break keyword at the end of each case statement to stop execution. Failing to do so will cause the execution of the statements that come under later case statements until it reaches the break statement or the end of switch. This seems odd, but it has its usefulness sometimes. • The selector expression in the switch statement won’t accept non-ordinal types such as strings. • The for(;;) loop is equivalent to a while(true) or while(1) loop. All are infinite loops. To quit such loops, use the break keyword.
Functions and Procedures As in Delphi, a function in C++Builder must be declared (prototyped) before it can be used. Unlike Delphi, C++Builder has no special keywords that are used to declare functions such as function and procedure. Table 1.5 shows examples of function declarations in both Delphi and C++Builder. TABLE 1.5
Delphi-to-C++Builder Function Declaration Comparison
Delphi
C++Builder
procedure Add;
void Add();
procedure Add(x, y: Integer);
void Add(int x, y);
function Add: Integer;
int Add();
function Add (x, y: Integer): Integer;
int Add (int x, y);
03 9721 CH01
4.6.01
1:59 PM
Page 39
Introduction to C++Builder CHAPTER 1
The main() function takes two parameters, argc and argv, and returns an integer value. It is unlike other functions in that it can’t be called directly; it is called automatically when the program starts running. Functions in C++ use an opening brace ({) to begin and a closing brace (}) to end. These braces are equivalent to Delphi begin and end keywords. In Figure 1.4 you can see that C++Builder uses the return keyword to return values. It will also cause the termination of the called function (main() in this case). You need to be careful here. Unlike Delphi’s Result keyword, return will terminate the function immediately, so any statements coming after it will be ignored.
FIGURE 1.4 The C++Builder code editor window for a new console application.
1 INTRODUCTION TO C++BUILDER
Any C or C++ program must have a main() function that will be the entry point of the program. For GUI applications it is called WinMain(). main() functions just like any other function: It takes parameters and returns values. Figure 1.4 shows the main() function when you create a new console application. Note that you can create a console application by choosing File, New, Console Wizard.
39
03 9721 CH01
40
4.6.01
1:59 PM
Page 40
C++Builder 5 Essentials PART I
Classes Delphi and C++Builder have the same way of controlling the access of functions. They hide these functions in structures called classes. Collecting functions in a class to accomplish a specific task is called encapsulation. From C, C++ inherited the struct keyword, which is almost identical to class. The only difference between structures and classes is that structure data members and member functions are public by default, whereas a class’s default is private. As in Delphi, a class in C++Builder has the following features: • Constructors and destructors • Access control to data members and member functions • A pointer called this, which is equivalent to self in Delphi One of the most powerful features of classes in C++ is that they can be built using multiple inheritance. Multiple inheritance is when a class is derived from two or more base classes. In Delphi (actually Pascal), classes are derived from a single base class. Let’s look at some of the class syntax for various types of inheritance: • No inheritance class MyClass { // no inheritance. // Private by default so anything declared here is private. private: // Private declaration protected: // Protected declaration public: // Public declaration }; // MyClass is terminated by semicolon.
• Single inheritance class MyClass: BaseClass1 {...};
• Multiple inheritance class MyClass: BaseClass1, BaseClass2, {...};
BaseClass3
Constructors and Destructors Every class has a constructor and a destructor. If the programmer does not write a specific constructor or destructor for the class, the compiler will create default ones.
03 9721 CH01
4.6.01
1:59 PM
Page 41
Introduction to C++Builder CHAPTER 1
A class can have more than one constructor, but it has only one destructor. Constructors and destructors are just like any other member functions of the class, but they have some special features: • They don’t return values (not even void). • The constructor takes the name of the class, and the destructor takes the name of the class preceded by the ~ symbol. For example class A { Public: A(); // Constructor ~A(); // Destructor }
• Constructors can take parameters as needed, but destructors take none. • They can’t be called as a normal function.
Accessing Data Members and Member Functions Assume you have the following simple class: class Rabbit { Private int speed=20; };
Later, you can declare it in your program using one of the following methods: Rabbit Rabbit1; Rabbit* Rabbit2 = new Rabbit; Rabbit1 is created on the stack, and Rabbit2 is created on the heap. You can access the speed data member for both of them using the direct access operator, as follows: Rabbit1.speed=30; (*Rabbit2).speed=30;
To make it easier to access data members of classes such as Rabbit2, C++ introduced the arrow operator (->). The above statement can be written as Rabbit2->speed=30;
The this Pointer Like the self pointer in Delphi, this is a hidden data member in all C++Builder classes. The following is an example of how to use the this pointer:
1 INTRODUCTION TO C++BUILDER
The constructor’s main purpose is to allocate space for the class and to initialize class data members. The destructor’s job is to free the allocated memory.
41
03 9721 CH01
42
4.6.01
1:59 PM
Page 42
C++Builder 5 Essentials PART I __fastcall TForm1::TForm1(TComponent* Owner) : TForm(Owner) { TLabel *Label1 = new TLabel(this); Label1->Parent = this; Label1->Caption = this->Width; // which is equivalent to Form1->Width; }
Preprocessor Directives Preprocessor directives are special instructions for the compiler. They are specified on a line that starts with the # symbol. Preprocessor directives are usually placed at the beginning of a unit. Many directives can be placed just about anywhere in the unit, but certain directives must be placed at a particular position within the unit, such as the #pragma argsused directive, which must be placed before the definition of the function to which it applies. We will look at the #define and #include preprocessor directives.
The #define Directive As shown in the “Constants” section, earlier in this chapter, the preprocessor command #define can be used to declare constants. The #define command is also used to create macros. Macros are just like any other function and can have parameters as follows: #define MAX(A,B) ((A)>(B)?(A): (B) #define MIN(A,B) ((A)>(B)?(B): (A)
You use them as follows: int x = y = max
x, y, max ; 5; 6; = MAX(x,y); // Remember that C++Builder is case sensitive.
The #include Directive Before we discuss the #include directive, you need to know the use of a header file. C++ uses a header file as an interface to source code files. Most of the time all declarations of constants, variables, and functions should be placed in the header files, and only the implementation part should be kept in the .CPP source file. During compilation, the #include directives will be replaced with the header file to which the directive is pointing. The syntax can take one of the following forms: #include #include “headerfile.hpp”
03 9721 CH01
4.6.01
1:59 PM
Page 43
Introduction to C++Builder CHAPTER 1
Types of Files Table 1.6 compares Delphi file types to those in C++Builder. TABLE 1.6
Delphi-to-C++Builder File Type Comparison
Delphi
C++Builder
Description
DPR
BPR
PAS
CPP
DFM
DFM
PAS
H
RES
RES
DCU
OBJ
BPG
BPG
DPK
BPK
None
BPI
BPL
BPL
The Builder project. Each unit has a source code file plus one main project file. A binary file that describes the form and all its components. A header file. A compiled binary resource file. Compiled binary object. Combination of projects in one group file. Source file listing the units used in the package. Import library file created for each package file. The runtime library. It’s like Windows DLL with special Builder features. Static library files. Backup files. A text file that contains information for which files the Builder needs to compile and link for this project. A text file that contains information used to perform low-level debugging tasks. Turbo Debugger Symbol—contains debugging information.
or HPP
None
LIB
~*
~*
None
MAK
MAP
MAP
None
TDS
The following points should help to clarify the file type comparisons in Table 1.6. • The first five types are created on the first Save of the project. • The CPP and HPP files are equivalent to the implementation and interface sections, respectively, of the PAS file.
1 INTRODUCTION TO C++BUILDER
The first statement tells the compiler to search for the headers only in the include files, which are set in Project, Options, Directories/Conditionals. In the second statement, the compiler will start searching for the headers in the current directory. Then it will continue searching in the include files.
43
03 9721 CH01
44
4.6.01
1:59 PM
Page 44
C++Builder 5 Essentials PART I
• The OBJ files are created when selecting Project, Compile Unit. The same type of file will be created when compiling a package. • The BPK file will be created when you save a package file. •
BPI, BPL,
and LIB files are created when a package is compiled or installed.
• In C++Builder 4 and C++Builder 5, MAK has been replaced by BPR. If you try to open MAK file in C++Builder 4 or higher, the IDE will convert it to a BPR file. • The TDS file contains debugging information. This file will get larger when the Project, Options, Compiler, Debug Information menu item is enabled.
Advantages and Disadvantages of C++Builder 5 In this section, we discuss some of the features of C++Builder that could affect a software engineering project. It would be fair to assume that the majority of this book’s readers will have settled upon C++Builder as their chosen development platform. The intention here is to highlight some of those features that make C++Builder such a useful tool, while bringing the reader’s attention to other issues that could cause difficulties.
Visual Reality: True Rapid Application Development For C++ programmers who require a truly visual environment for designing applications with rich, professional-looking user interfaces, the C++Builder IDE with the accompanying Visual Component Library is the only comprehensive, integrated solution. C++Builder’s array of project templates helps get a new program up and running in under a minute, and there is no faster way to start Windows programming in C++. The Object Repository provides an invaluable way to reuse code for productivity and consistency. Even a moderately experienced user will be able to create a simple multifile text editor with menus, toolbars (that can dock or float), and other basic features, all in half an hour. Not only is this astoundingly productive, it can be lots of fun. Being able to see how your application looks while you are designing it reduces the need for trial and error. C++Builder 5 adds some new features to those seen in previous versions that make visual development even easier. For example, the TFrame component allows you to work with independent, reusable form-like windows that can then be placed within forms or even on the Component Palette for later use. Improvements to the Object Inspector include enhanced editors for TColor and TCursor properties, as well as property and event lists that are now categorized to allow infrequently used sets of items to be hidden. This makes it easier to find what you are looking for. On the left side of Figure 1.5, the TCursor property editor in the Object Inspector is shown at work in a project containing two frames that are being used within the main form.
03 9721 CH01
4.6.01
1:59 PM
Page 45
Introduction to C++Builder CHAPTER 1
45
1 INTRODUCTION TO C++BUILDER
FIGURE 1.5 Some of the new visual development enhancements in C++Builder 5.
Microsoft’s Visual C++, although “visual” in name, does not offer this WYSIWYG method of development. This is perhaps the most significant advantage of C++Builder over Visual C++. Visual C++ users have two realistic alternatives for Windows application development. One is to develop programs with the supplied resource editor and the Microsoft Foundation Classes (MFC) library. The other is to develop back-end code as a dynamic link library (DLL) to be used by a graphical user interface (GUI) created in another development environment better suited to visual programming, for example Microsoft’s own Visual Basic language. The first option does not offer a great deal of visual interaction. While the use of the resource editor allows dialog boxes to be laid out in a way similar to C++Builder’s form designer, the variety of ways in which controls can be manipulated at designtime in C++Builder is far more powerful. In fact, C++Builder also comes with the MFC, which is included for those rare times when it would be preferred, though the main reason for its inclusion is for compatibility with existing MFC code. (Visual C++ does not provide a migration path from C++Builder.) Furthermore, only standard controls are catered to by the resource editor, while C++Builder’s system can support the thousands of additional VCL components that are available. The MFC is a very “thin” wrapper around the Windows Application Programming Interface (API) and, although it is more complete in its coverage of the API than the VCL, it does not provide the same high level of built-in functionality and places the burden on the programmer.
03 9721 CH01
46
4.6.01
1:59 PM
Page 46
C++Builder 5 Essentials PART I
The other option actually does present certain benefits in that, from an architectural point of view, the separation of an application’s “engine” from its user interface can provide flexibility and expandability. Nevertheless, the capability of C++Builder to serve well as both a C++ compiler and a visual GUI designer supports its claim to be the most productive of the two systems. A well-engineered program written in C++Builder can support the GUI separation idea equally well.
Keeping Up with the Joneses: The C++ Standard For many years now, Borland has been several strides ahead of the pack in ensuring that its compiler is up to date with the latest ANSI/ISO standards. C++Builder 5—built upon the version 5.5 model of the Borland 32-bit C++ compiler (BCC32)—is no exception. The current details of the language are formalized in the latest ANSI/ISO specification. It differs from the previous version of the standard in several respects, notably in the areas of C++ templates and namespaces. This may not mean a great deal in small, monolithic applications developed prototypically and largely within the confines of the form designer. However, for a serious application that has been designed with scalability in mind, a compiler as rigorous and standard-compliant as BCC32 is crucial to the long-term success of a project. As a consequence of Borland’s policy on the issue of continual improvements to its back-end compiler, however, some developers will find that existing programs that correctly compile under previous versions of C++Builder will fail to do so under version 5. This problem is likely to manifest itself only in cases where heavy use is made of a feature whose treatment by the compiler has undergone a particularly major change, such as templates. I speak from first-hand experience, having spent time converting such an application created in C++Builder 3 to run under version 4 and then again to version 5. Although this particular application has been exposed as being badly written in some places—a good thing to be aware of as a developer and certainly food for thought—it did set my project back. As a keen software engineer and one who is learning all the time, I found the experience to be a positive one. Unfortunately, in such circumstances, project management and the all-important customer may not be quite so enthused. The moral of this story is that the long-term benefits of the compiler can be greatly appreciated, but one cautious eye needs to stay on the here and now. C++Builder also extends the compiler to support proprietary (that is, non-portable) extensions to the C++ language in order to support the VCL. While in many circumstances you may choose to avoid them for reasons of portability, this is another string in the bow of the compiler. For example, the __closure keyword, which supports the concept of a member-function pointer for an instance and not a class, can be useful, because there is no clean way to achieve a similar effect within the scope of the current C++ specification. See the “keyword extensions” reference on the “__closure” page in the online help for more information.
03 9721 CH01
4.6.01
1:59 PM
Page 47
Introduction to C++Builder CHAPTER 1
47
Choosing the Right Development Environment
1
Whatever claims are made by compiler vendors, no one platform is perfect. There will always be supporters who back one side and find only fault with the other. As a piece of software evolves over time, it is inevitable that problems will arise that will reveal flaws in the chosen development tool. This is a fact of life for a developer.
INTRODUCTION TO C++BUILDER
C++Builder 5 is a development tool, not a panacea for all our programming troubles. Of course, this is not exclusive to C++Builder, and there are areas of software development to which it is ideally suited and superior to its competitors and other to which it is not. Having said this, there is no disputing that C++Builder 5 is a robust and intuitive development environment that can be an immensely powerful and productive solution. For those developers who go the Microsoft route, there may be very pressing reasons for doing so—or the dominant reason may simply be that Borland is not Microsoft. By the time you read this, it is expected that Borland will have ported C++Builder to run under the Linux operating system. The potential to write multiplatform applications is sure to interest many people and sway them toward the product. See the section “Preparation for Kylix,” later in this chapter.
C++Builder Advantages and Disadvantages Conclusion It is possible to draw some useful conclusions from this discussion. While the following lists are by no means exhaustive, we can identify some particular advantages and disadvantages to C++Builder. We have not focused on database or Internet features, which are also key selling points of C++Builder, but they do appear in the following list. A summary of the advantages of C++Builder 5 is provided in the following list: • It is a powerful form designer. • It is suitable for both traditional C++ programming and rapid user interface development, because it integrates an ANSI/ISO–compliant compiler with a truly visual development environment. • Its comprehensive Visual Component Library can be supplemented through acquisition of third-party components (including Delphi components) and by creating your own. • Proprietary C++ extensions support additional programming constructs. • Project templates and the Object Repository allow for quick project setup and reuse. • Easy-to-use database support is provided through data-aware components and the Borland Database Engine. • It provides powerful support for Internet development.
03 9721 CH01
48
4.6.01
1:59 PM
Page 48
C++Builder 5 Essentials PART I
• Migration from Visual C++ to C++Builder is relatively straightforward. • It provides a possible route for porting applications to Linux. A summary of the disadvantages of C++Builder 5 is provided in the following list: • The form designer’s ease of use can encourage a haphazard program structure if its design is not in place early on. • Due to changes in the compiler, it might not be worth upgrading from earlier versions if a program is going to require major changes to compile under version 5. • Migration from C++Builder to Visual C++ is usually very difficult. • Choosing a Borland product over Microsoft may have long-term consequences due to Microsoft’s general domination of the industry.
Preparation for Kylix Kylix is the internal code name for Borland’s development environment for the Linux operating system. (The official product name has not yet been announced at the time this is being written.) In basic terms, it is “Delphi and C++Builder for Linux.” With Kylix you can develop applications for Linux systems as easily as you can currently develop Windows applications with C++Builder. It will be possible to port many of your existing C++Builder applications to Linux. There are many similarities between Kylix and C++Builder (and Delphi), but there are also some important differences, mostly brought about by the differences between the Windows operating system and the Linux operating system. We’ll take a look at some of these to alert you to new possibilities with C++Builder. If you are considering porting your applications to Linux, you should be aware of the similarities and differences between Kylix and C++Builder. When I was in the Boy Scouts, we had a simple motto: “Be Prepared!” I still think that it is a great motto, and in the game of software development it’s something that we should keep in mind. Note that what is presented in the remainder of this section is based on information from public announcements and discussions of Kylix available at the time of writing this book. The information here should be considered speculative, because the product is not yet complete, and most of the features and specific details have not been publicly released.
Similarities Between Kylix and C++Builder The basic framework for Kylix will be very similar to C++Builder in most respects. Apart from the general differences between the Windows user interface and the various Linux user interfaces available, the IDE in both products will be almost identical. There will be the Object
03 9721 CH01
4.6.01
1:59 PM
Page 49
Introduction to C++Builder CHAPTER 1
FIGURE 1.6 The Kylix IDE, displayed in Linux using the K Desktop Environment.
Just as C++Builder shares a lot of common functionality and look-and-feel with Delphi, my guess is that the addition of Kylix into the pool will result in common core features being shared among all three products. As new features are implemented in any one of the products, those features will be available in the others in the next release. In the C++Builder version of Kylix, you’ll still be writing C++ code just as you do today. You’ll hardly notice the difference. After all, C++ is C++.
Differences Between Kylix and C++Builder Because Linux is not Windows, there are some features in C++Builder that we won’t see in Kylix, at least initially. These Windows-specific technologies include COM, DCOM, COM+, ActiveX, and Win32 API calls. A few years ago, Microsoft, Digital, and another large company were developing DCOM for UNIX servers. If it’s not available already, then it’s only a matter
1 INTRODUCTION TO C++BUILDER
Inspector, a class browser, various component tabs in the Component Palette, and a code editor. You will be able to reuse what you’ve already learned with C++Builder. Figure 1.6 is a very early (pre-release) screenshot of a Delphi project loaded into Kylix. The K Desktop Environment (KDE) of Linux is being used. Note the similarities to the C++Builder IDE.
49
03 9721 CH01
50
4.6.01
1:59 PM
Page 50
C++Builder 5 Essentials PART I
of time before it is. It is possible that SOAP (Simple Object Access Protocol) support will be included at some stage. I’m guessing that many of the Win32 API calls will have an equivalent in Linux, either transparently using a system API layer or specific to Linux. The latter would make porting of applications between the two more difficult. The VCL for Linux will be named the Borland Component Library for Cross Platform (CLX for short, pronounced “clicks”). The various CLX components will be grouped into logical units such as visual components, data access components, and so on. The GUI components will be built on TrollTech’s Qt framework. Qt is a cross-platform C++ GUI application framework that was selected by Borland as the most suitable framework to use in the Linux environment. Qt is installed with the KDE but must be installed separately when using Gnome or other Linux desktops. CLX will appear in the Windows versions of C++Builder and Delphi to facilitate easier porting of applications between Linux and Windows. However, for performance reasons, the VCL should still be used if the target operating system for the application is Windows. Kylix will include a new thin database access layer, likely to be called DBExpress, as a replacement for the Borland Database Engine (BDE). The current discussion suggests that it will support a limited set of underlying databases and require only a single DLL to be installed with the client.
Porting C++Builder Projects to Kylix Porting C++Builder projects to Kylix will depend on the features that are implemented in Kylix. The previous sections should give a general feel of the types of porting issues you’re likely to find. Porting most applications will definitely be possible. It would be great if it were possible without source code modifications but, realistically, many applications will require at least some basic tweaking.
So When? Based on current discussions, the Delphi version of Kylix will be released in early 2001. By the time you’re reading this, it may already be released, and you will know more about it than I do! The C++Builder version? Current discussions put that at mid 2001.
03 9721 CH01
4.6.01
1:59 PM
Page 51
Introduction to C++Builder CHAPTER 1
51
Summary
1
In this chapter, you learned the basics of C++Builder for beginners and those moving from Delphi. If this was your first look at C++Builder, you should now be able to see its enormous potential for developing Windows applications. You were also introduced to some of the new features and enhancements in C++Builder 5 and some of the upgrading and compatibility issues when migrating existing projects and third-party tools. Finally, you learned a little about Kylix, Borland’s upcoming product for software development on the Linux platform.
INTRODUCTION TO C++BUILDER
Several of the concepts discussed in this chapter will be covered in detail in the following chapters, and many new concepts will be introduced.
03 9721 CH01
4.6.01
1:59 PM
Page 52
04 9721 CH02
4.6.01
1:59 PM
Page 53
C++Builder Projects and More on the IDE Jamie Allsop Yoto Yotov Jarrod Hollingworth Khalid Almannai Dan Butterfield
IN THIS CHAPTER • Understanding C++Builder Projects • Using the Object Repository • Understanding and Using Packages • Introducing New IDE Features in C++Builder 5
CHAPTER
2
04 9721 CH02
54
4.6.01
1:59 PM
Page 54
C++Builder 5 Essentials PART I
In Chapter 1, “Introduction to C++Builder,” we introduced you to the IDE and projects, both integral parts of C++Builder. In this chapter we will build on Chapter 1. First we will look at projects in more detail, focusing on the various files included in a project and the Project Manager. Then we will show you how to use the Object Repository to store and reuse code and other program elements that you’ve developed. We also will discuss Packages, a special type of dynamic link library (DLL), and how they provide functionality in the IDE and in your applications. Finally, we will look at several great new features in the C++Builder 5 IDE.
Understanding C++Builder Projects C++Builder makes programming easier than ever. The Integrated Development Environment (IDE), introduced in Chapter 1, provides two-way development by integrating a graphical Form Designer and a Code Editor, allowing you to develop applications from two angles. Using the ClassExplorer, Code Insight, and standard features of the Form Designer, C++Builder can even write a lot of the mundane code for you! You can use C++Builder to develop applications such as those in the following list: • Windows or console applications • Client/server applications • Dynamic link libraries (DLLs) • Custom components and Packages • Component Object Model (COM) and ActiveX controls All these applications are created using projects. A project is a collection of C++ source files, form files, and other file types that together define the application. C++Builder uses a special project file to store the structure of the project and to remember various project options that change the way the application is built.
Files Used in C++Builder Projects C++Builder projects consist of many different types of files. Some files are created automatically by C++Builder, such as when a new project is started or when new items are added to an existing project. Other files are created by the developer, and there are other files that are created when the application is compiled. These files can be categorized as follows: • Main project files • Form files • Package files
04 9721 CH02
4.6.01
1:59 PM
Page 55
C++Builder Projects and More on the IDE CHAPTER 2
55
• The desktop options file • Backup files
Main Project Files When you create most projects, three main files are automatically created. They are shown in the following list: • C++Builder project file ProjectName.bpr • Main project source file ProjectName.cpp • Main project resource file ProjectName.res
By default your project is named Project1. You can change the name of the project when you first save it by renaming the Project1.bpr file in the Save Project As dialog that appears. You should be careful naming the various files in your project, using the same name for the main project files and other unit files can become confusing, and in some cases can hinder the ability to view the files in the Code Editor. The C++Builder Project File The project file is a text file that contains the project options settings and the rules to build the project. This file has changed somewhat through the different versions of C++Builder. In C++Builder 1 through 4, the file was in a Makefile format. In C++Builder 1 the project file actually had the extension .mak to signify this. In C++Builder 5 the file changed to the Extensible Markup Language (XML) format. For more information on the new XML project file format, see “The XML Project File Format,” later in this chapter. The Main Project Source File This file contains the application entry (startup) code, macros such as USEUNIT and USEFORM that define various files that are built with the application, and little else. C++Builder automatically maintains the macros throughout development. In a standard Windows application, the main project source file contains the WinMain() function as the application entry-point. In other types of applications, this function may be named DllEntryPoint() or simply main(). Unlike most other auto-generated source files, this file has no corresponding header (.h) file. You’ll seldom need to change the main project source file except to execute a function as the application starts, such as displaying a splash screen while the application is initializing. The Project Resource File This file contains the application’s icon, the application version number, and other information. Not all application types have a project resource file.
C++BUILDER PROJECTS
The files are initially created internally for you to start using. The files will not be created on disk until you save the project.
2
04 9721 CH02
56
4.6.01
1:59 PM
Page 56
C++Builder 5 Essentials PART I
Resource files in general store images, icons, and cursors for your project. To create these items, you typically use a tool like the Image Editor provided by C++Builder. Resource files can also contain strings and other objects. For a more in-depth look at storing images in a resource file, see “Using Predefined Images in Custom Property and Component Editors” in Chapter 10, “Creating Property and Component Editors.”
Form Files For each Form you create, C++Builder generates the following files: • The Form layout file UnitName.dfm • The Form source file UnitName.cpp • The Form header file UnitName.h By default the unit name is Unit1 for the first Form created, Unit2 for the second, and so on. You can rename the Form files when saving the project. The extension .dfm stands for Delphi Form, a reminder that C++Builder is based partially on Borland’s Delphi product. The .dfm file contains values that represent the graphical part of the Form, such as component locations, font styles, and so on. In C++Builder versions 1 through 4, the .dfm file is saved in a binary format. It can be viewed as text in these versions by right-clicking on the Form and then selecting View As Text. In C++Builder 5, the .dfm file is saved in a text format by default, but it can be saved in binary format if required. For more information see the “Forms—Save as Text” section, later in this chapter. You can edit the .dfm Form files if you want, but you rarely need to do so. The .cpp file and its associate .h header file are created with the .dfm file each time you create a new Form. The .h file contains the C++ class definition for the Form. The .cpp file contains the event handler functions for the Form and for the components that you add to the Form. In simple applications, most of the code that you write will be placed in the Form’s .cpp file. To view the .cpp and .h files, do the following: 1. If your project is not open, select File, Open. 2. Select View, Units, then choose the unit file of your Form and click OK or press Enter. The .cpp file for the Form will be displayed in the Code Editor. 3. To view the header file, right-click in the Form’s .cpp file displayed in the Code Editor and choose Open Source/Header File.
The Package Files Packages are simply dynamic link libraries (DLLs) that can be shared among many C++Builder applications. They allow you to share classes, components, and data between applications. For example, the most frequently used C++Builder components reside in a
04 9721 CH02
4.6.01
1:59 PM
Page 57
C++Builder Projects and More on the IDE CHAPTER 2
57
Package called VCL50. Most applications created in C++Builder share some common code from this Package, provided in the Package file vcl50.bpl. The following are specific Package files: • The Package Project Options (.bpk) file. Consider this file to be like a .bpr project file, but applicable only for Packages. This file is created if you choose File, New, Package. • The Borland Package Library (.bpl) file.
• The Borland Package Import Library (.bpi) file. Each time you compile the Package source file, a .bpi file will be created. Again, its base name matches the Package source base name. See the “Understanding and Using Packages” section later in this chapter for more information on Packages.
The Desktop Options File The desktop options file for a project stores the arrangement of the various windows open in the IDE and the files open in the Code Editor. The next time the project is opened, these settings will be restored. The Desktop options filename has the format ProjectName.dsk and is saved in the same folder as the project. C++Builder can be set to save the file automatically when you close the project. From the menu, select Tools, Environment Options. This will take you to the Environment Options dialog. Select the Preferences tab and check AutoSave Options, Project Desktop.
Backup Files C++Builder will create a backup file for each of your project’s .bpr, .dfm, .cpp, and .h files each time you save your project, except for the first save. All backup file extensions are prefixed with the ~ symbol; thus, the .bpr file extension will become .~bp, .cpp will become .~cp, and so on.
Project Manager The Project Manager displays the file structure of a project or project group. The Project Manager can be viewed by selecting View, Project Manager from the C++Builder menu. Figure 2.1 shows an example of the Project Manager dialog.
2 C++BUILDER PROJECTS
This is the resulting runtime library for the Package. It is like a DLL, except that it contains C++Builder-specific features. Its base name matches the Package source base name.
04 9721 CH02
58
4.6.01
1:59 PM
Page 58
C++Builder 5 Essentials PART I
FIGURE 2.1 The Project Manager window for C++Builder.
A project group is a collection of projects. Sometimes you need to create more than one project for an application. For example, an application could have a VCL project, a DLL project, and a console project. The information about the project group is stored in a project group file in the same folder as the project. It has the filename ProjectName.bpg. The main functions of the Project Manager are shown in the following list: • Adding or removing projects • Adding or removing forms or units • Drag-and-drop capability • Selecting a project • Compiling or building all your projects
Using the Object Repository One of C++Builder’s most powerful project management tools is the Object Repository. It lets you share and reuse forms, projects, data modules, project templates, and wizards. For example, if you need to develop a series of applications that share a standard About dialog box, you can store the dialog box in the Object Repository. This allows you to add the dialog to all projects quickly, saving time and avoiding the need to copy or redesign the dialog each time.
Adding Items to the Object Repository Let’s take as our first example the standard About dialog box described previously, or the About box for short. We will use as a base the standard About box available in C++Builder. To design and test it, we first need to create a simple application that will act as the host of the
04 9721 CH02
4.6.01
1:59 PM
Page 59
C++Builder Projects and More on the IDE CHAPTER 2
59
About box. Select File, New Application. To add the default About box to the application, select File, New, Forms, About Box. We want to customize this default About box by changing the captions of the labels to appropriate values at runtime. Figure 2.2 shows how we want our standard About box to look. It contains a logo, the correct name and version of the product that is using the About box, and a comment. We’ve kept the default logo, but it too can be customized if desired.
2 C++BUILDER PROJECTS
FIGURE 2.2 Our standard About dialog box.
If you followed the previous steps to create a new About box, you’ll notice that, in addition to the customized label captions, we have deleted the copyright label. We have done this simply to demonstrate that you can make whatever changes you want. The copyright label can be removed by selecting Copyright Label in the Form Designer and pressing Delete. Name the About box StdAboutBox by selecting About Box in the Form Designer and entering this text next to the Name property in the Object Inspector. Save the entire C++Builder project by selecting File, Save All. In the Save As dialog, change the name of the About Box unit from Unit2.cpp to StdAboutBox.cpp. Change the name of the application’s main form unit from Unit1.cpp to AboutTestForm.cpp, and change the name of the project source file to AboutTestProj.cpp. To set the label captions of the About box at runtime, add some code to the OnCreate event handler of the About box. With the About box selected in the Form Designer, click on the Events tab in the Object Inspector and double-click next to the OnCreate event. Add the code in Listing 2.1 to the TStdAboutBox::FormCreate() event handler function that appears in the Code Editor. LISTING 2.1
The OnCreate Event Handler Function for TStdAboutBox
void __fastcall TStdAboutBox::FormCreate(TObject *Sender) { struct TransArray { WORD LanguageID, CharacterSet;
04 9721 CH02
60
4.18.01
3:39 PM
Page 60
C++Builder 5 Essentials PART I
LISTING 2.1
Continued
}; DWORD VerInfo, VerSize; HANDLE MemHandle; LPVOID MemPtr, BufferPtr; UINT BufferLength; TransArray *Array; char QueryBlock[40]; // Get the product name and version from the // applications version information. String Path(Application->ExeName); VerSize = GetFileVersionInfoSize(Path.c_str(), &VerInfo); if (VerSize > 0) { MemHandle = GlobalAlloc(GMEM_MOVEABLE, VerSize); MemPtr = GlobalLock(MemHandle); GetFileVersionInfo(Path.c_str(), VerInfo, VerSize, MemPtr); VerQueryValue(MemPtr, “\\VarFileInfo\\Translation”, &BufferPtr, &BufferLength); Array = (TransArray *)BufferPtr; // Get the product name. wsprintf(QueryBlock, “\\StringFileInfo\\%04x%04x\\ProductName”, Array[0].LanguageID, Array[0].CharacterSet); VerQueryValue(MemPtr, QueryBlock, &BufferPtr, &BufferLength); // Set the product name caption. ProductName->Caption = (char *)BufferPtr; // Get the product version. wsprintf(QueryBlock, “\\StringFileInfo\\%04x%04x\\ProductVersion”, Array[0].LanguageID, Array[0].CharacterSet); VerQueryValue(MemPtr, QueryBlock, &BufferPtr, &BufferLength); // Set the version caption. Version->Caption = (char *)BufferPtr; GlobalUnlock(MemHandle); GlobalFree(MemHandle); } else { ProductName->Caption = “”; Version->Caption = “”; } Comments->Caption = “Thank you for trying this fabulous product.\n” “We hope that you have enjoyed using it.”; }
This code retrieves the product name and product version from the project’s version information. To add version information to the project, select Project, Options, then click on the
04 9721 CH02
4.6.01
1:59 PM
Page 61
C++Builder Projects and More on the IDE CHAPTER 2
61
Version Info tab and check the Include Version Information in Project option. Scroll down to the ProductName field in Key/Value table and enter a product name such as My Demo Product. By default the project starts with version 1.0.0.0. Click OK to close the Project Options dialog. Later, when the About box is added to any project, the correct version information for that project will be displayed without the need to change any code in the About box. In Listing 2.1, a long caption has been assigned to the Comments label. To display this caption, select the Comments label in the Form Designer, click on the Properties tab in the Object Inspector, and change the Width and Height properties to 265 and 35, respectively. Set AutoSize to false. The creation of our standard About box is now complete.
void __fastcall TForm1::Button1Click(TObject *Sender) { StdAboutBox->ShowModal(); }
The complete AboutTestForm.cpp unit is shown in Listing 2.2. LISTING 2.2
The Complete AboutTestForm.cpp Unit
//--------------------------------------------------------------------------#include #pragma hdrstop #include “AboutTestFOrm.h” #include “StdAboutBoxForm.h” //--------------------------------------------------------------------------#pragma package(smart_init) #pragma resource “*.dfm” TForm1 *Form1; //--------------------------------------------------------------------------__fastcall TForm1::TForm1(TComponent* Owner) : TForm(Owner) { } //---------------------------------------------------------------------------
C++BUILDER PROJECTS
To test the About box, we need to display it from the test application to which we added it. To do this, click on the AboutTestForm.cpp tab in the Code Editor. Add the line #include “StdAboutBoxForm.h” immediately after the #include “AboutTestForm.h” line at the top of the unit. Add a Button component to the middle of the test Form in the Form Designer, and create an OnClick event handler for the button by double-clicking the button. In the event handler, add the following code.
2
04 9721 CH02
62
4.6.01
1:59 PM
Page 62
C++Builder 5 Essentials PART I
LISTING 2.2
Continued
void __fastcall TForm1::Button1Click(TObject *Sender) { StdAboutBox->ShowModal(); } //---------------------------------------------------------------------------
This code will display our About box when the button on the test Form is clicked at runtime. Using ShowModal(), the About box must be closed before the user can return to the test Form. Save all changes to the project by selecting File, Save All. You can find the complete example, with the project filename AboutTestProj.bpr, in the ORAboutBox folder on the CD-ROM that accompanies this book. Now compile and run the application by selecting Run, Run or pressing F9. When you click on the button, the About box is displayed. You should see an About box similar to that shown in Figure 2.2. Click OK to close the About box and return to the test Form. Close the test Form to stop the application. Now that our About box has been tested and is working correctly, we can add it to the Object Repository. Items added to the Object Repository appear in the File, New dialog. First, rightclick on the About box in the Form Designer and select Add To Repository from the pop-up menu. Specify a title and description. In the Page combo box, select an appropriate page of the Object Repository to add the About box to, such as Forms. Enter your name in the Author field and, if you like, specify an icon to display for this Form. Click OK to save the About box to the Object Repository. At this point, if you select File, New and click on the Forms tab, you should see the standard About box you just created.
FIGURE 2.3 The Add To Repository dialog.
In addition to forms, entire projects can be added to the Object Repository. This is done by selecting Add To Repository from the Project menu.
04 9721 CH02
4.6.01
1:59 PM
Page 63
C++Builder Projects and More on the IDE CHAPTER 2
63
NOTE Before adding items, make sure you save the current form or project. Unsaved items cannot be added to the Object Repository. If you forget to save the item before adding to the Object Repository, C++Builder will prompt you to do so. If an item with the same name already exists in the Object Repository, C++Builder will prompt you to replace it.
2 To access any of the items previously added to the Object Repository, choose File, New from the main menu. As you can see, the Object Repository has various pages, each of which contains reusable items.
TIP The items shown on each tab of the Object Repository List can be displayed in various formats. Right-click on the Object Repository dialog to see the list of available view styles. For example, you can select View Details to display the name, description, modified date and time, and author of each item in a tabular format.
At the bottom of each page, you’ll find three radio buttons: Copy, Inherit, and Use. These buttons demonstrate the power and flexibility of the Object Repository. The Copy option creates a duplicate of an item you select. Changes made to the duplicate will not affect the Object Repository. In the same way, changes to the original item will not affect the duplicate. The Inherit option is similar to Copy. The difference is that the new object is derived from the original. Therefore, changes in the Object Repository original will be reflected in your copy. Finally, the Use option opens and edits the selected Object Repository item directly. Using items directly is not recommended unless you’re dealing with data modules.
Sharing Items Within a Project If you display the File, New dialog and a project is currently open, you’ll find a tab with the name as your project. This tab lists all forms and data modules available in your project. The Object Repository allows you to inherit from existing forms. This feature is particularly helpful if you have to create several similar forms a project.
C++BUILDER PROJECTS
Using Items in the Object Repository
04 9721 CH02
64
4.6.01
1:59 PM
Page 64
C++Builder 5 Essentials PART I
Customizing the Object Repository You can organize items and pages displayed in the Object Repository using the Object Repository Options dialog box. To display it, select Tools, Repository or right-click the File, New dialog and choose Properties from the context menu.
FIGURE 2.4 The Object Repository dialog.
The first list box contains a list of all available pages. With the arrow buttons, you can change the position of the selected page. In addition, you could add, remove, or delete pages with the appropriate buttons on the right.
NOTE Only empty pages can be removed. Before deleting a page, remove all objects it contains.
The second list box contains all items in the selected page. This time only two buttons are available: one to delete the object and another to edit its description. Depending on the object type, the following options may be available: • New Form Opens the specified default form when you click File, New Form. • Main Form Opens the specified default main form when a new project is created. • New Project Opens the specified default new project when you click File, New Application.
Creating and Adding a Wizard to the Object Repository Wizards (also known as experts) are simple applications that lead you through various dialog boxes and help you create projects or code snippets or simply display information. C++Builder
04 9721 CH02
4.6.01
1:59 PM
Page 65
C++Builder Projects and More on the IDE CHAPTER 2
65
comes with a variety of wizards, such as the Console Wizard and the MFC Wizard, which you may have used before. We’ve seen in the previous pages how to create and add forms and projects to the Object Repository. Obviously, wizards require closer integration with the C++Builder IDE. They do this using the Open Tools API TIExpert interface.
NOTE
To create a wizard, you must define a descendant of the TIExpert class. Each of the TIExpert member functions will then gather information about the new wizard. These member functions are: GetName(), GetAuthor(), GetComment(), GetPage(), GetGlyph(), GetStyle(), GetState(), GetIDString(), GetMenuText(), and Execute(), as well as a constructor and a destructor. Again, a complete description can be found in the OTA source files. Wizards can be compiled in a package (described in the next section, “Understanding and Using Packages”) or in a DLL. I’ll use a Package, which is easier to install and manage. The first step is to create a new Package from the Object Repository by selecting File, New, and then selecting Package from the New tab. Edit the Package’s source file, Package1.cpp, adding the #include <ExptIntf.hpp> line, TWizard class, TWizard::Execute() function, and namespace sections shown in Listing 2.3. You can find the complete Package, with the filename MyWizard.bpk, in the ORWizard folder on the CD-ROM that accompanies this book. LISTING 2.3
Source Code for MyWizard.cpp
//--------------------------------------------------------------------------#include #include <ExptIntf.hpp> #pragma hdrstop USERES(“MyWizard.res”); USEPACKAGE(“vcl50.bpi”); //--------------------------------------------------------------------------#pragma package(smart_init) //---------------------------------------------------------------------------
2 C++BUILDER PROJECTS
The Open Tools API (OTA) is composed of eight units, each of which provides interfaces for interaction with the IDE. Although the OTA is not officially documented, the best way to master it is to look at its source code, found in the \Source\ToolsAPI folder where C++Builder was installed.
04 9721 CH02
66
4.6.01
1:59 PM
Page 66
C++Builder 5 Essentials PART I
LISTING 2.3
Continued
// Package source. class __declspec(delphiclass) TWizard : public TIExpert { public: String __stdcall GetName() {return “My Wizard”;}; String __stdcall GetAuthor() {return “Yoto Yotov”;}; String __stdcall GetComment() {return “A sample wizard”;}; String __stdcall GetPage() {return “New”;}; HICON __stdcall GetGlyph() {return hIcon;}; TExpertStyle __stdcall GetStyle() {return esProject;}; TExpertState __stdcall GetState() {return TExpertState() << esEnabled;}; String __stdcall GetMenuText() {return “Wizard”;}; String __stdcall GetIDString() {return “Yotov.Wizard”;}; virtual void __stdcall Execute(void); __fastcall TWizard() {hIcon = LoadIcon(NULL, IDI_APPLICATION);}; virtual __fastcall ~TWizard() {}; protected: HICON hIcon; }; void __stdcall TWizard::Execute() { Application->MessageBox(“Wizard is available!”, “Congratulations!”, MB_OK); } #pragma argsused int WINAPI DllEntryPoint(HINSTANCE hinst, unsigned long reason, void*) { return 1; } //--------------------------------------------------------------------------namespace Mywizard
04 9721 CH02
4.6.01
1:59 PM
Page 67
C++Builder Projects and More on the IDE CHAPTER 2
LISTING 2.3
67
Continued
{ void __fastcall PACKAGE Register() { RegisterLibraryExpert(new TWizard()); } }
This code implements the required TIExpert member functions; for instance, the GetName() function sets the name of our wizard in the Object Repository to My Wizard, and the GetPage() function sets the page that it will appear on to New.
Now, open the File, New dialog and admire the wizard you’ve just created. It will appear with the name My Wizard. Of course, more coding is required in the Execute() member function to make your expert useful. I leave that to you.
Understanding and Using Packages This section discusses Packages and how they are used both in applications and by the IDE. The term Package refers specifically to a source module with the .bpk extension (Borland Package) and more generally to a Borland Package Library (BPL) file (.bpl extension) that is created when the Package is built. A BPL file is very similar to a dynamic link library (DLL) and is used for the same purpose, to dynamically link executable code to an application. For more information on the similarities and differences between a Borland Package Library and a dynamic link library, refer to Chapter 15, “DLLs and Plug-Ins,” which covers this topic in more depth. A Package can be one of three types: designtime-only, runtime-only, or dual designtime/ runtime. Essentially, the only difference between these Packages is that a designtime Package can be installed into the IDE, and a runtime Package cannot. Runtime Packages can be used only at runtime. The dual Package can be used in either situation and is often used for convenience when initially developing components. Using Packages as a method for deploying components makes up the bulk of the “Distributing Components and Other Issues” section in Chapter 11, “More Custom Component Techniques.” A Package consists of two sections: a Contains section and a Requires section. Files that appear in the Contains section are those that the Package contains, which are compiled and linked when the Package itself is compiled and linked. These files are part of the Package.
C++BUILDER PROJECTS
To add our wizard to the Object Repository, we need to compile and install it. Display the Package Editor by selecting View, Toggle Form/Unit or pressing F12 while in the Code Editor. Click the Compile button in the Package Editor, and when the compile is finished press OK. To install the Package, simply click the Install button in the Package Editor. A message box will appear to tell you that the Package has been installed.
2
04 9721 CH02
68
4.6.01
1:59 PM
Page 68
C++Builder 5 Essentials PART I
Import files appearing in the Requires section are references to runtime Packages that this Package must access to function correctly. This mechanism will be explained more clearly later in this section. When a Package is built, all the files in the Contains section, where appropriate, are compiled and linked, and object files for each are created. In addition, a BPL file is generated, as are a Borland Package Import (BPI) file (.bpi extension) and a static library (LIB) file (.lib extension). To not generate a BPI file, select the Linker tab in the Project, Options dialog, and uncheck the Generate Import Library option in the Linking group. To not generate a LIB file, uncheck the Generate .lib File option. You always need to generate a BPI file, which is used by the IDE during linking, so that the executable can use the respective BPL file at runtime. This is true except in a designtime-only Package. Therefore, the same types of files are produced for all Package types. The difference is only apparent in their use. Figure 2.5 shows the structure of a Package and the files that are produced upon a successful build. Package
PackageName. bpk
Files Created on a Successful Build
Contains PackageName.bpl PackageName.cpp ContainedUnit1
PackageName.bpi PackageName.lib
ContainedUnit2
• • • ContainedUnitn
ContainedUnit1.obj ContainedUnit2.obj
• • • ContainedUnitn.obj
Requires vcl50.bpi
FIGURE 2.5 The structure and output of a Package.
Note that in Figure 2.5, the contained units are implied to be C++ translation units. Hence, for each translation unit, an object file is produced when the Package is compiled and linked successfully. Other files can also be added to a Package’s Contains section, most notably resource files and object files. These files are commonly needed when a Package is used to Package components. For more details on this, refer to Chapter 11. The Requires section in Figure 2.5 includes the import file vcl50.bpi. This indicates that the Package requires executable code contained by vcl50.bpl (the core VCL runtime BPL).
04 9721 CH02
4.6.01
1:59 PM
Page 69
C++Builder Projects and More on the IDE CHAPTER 2
69
Placing the vcl50.bpi import file in the Package’s Requires section allows the linker to resolve any external references to the vcl50.bpl runtime library. Nearly all the Packages that you create will use the core VCL, in which case you will need this import file in the Requires section of nearly all the Packages you create.
For an application to link dynamically to a .bpl file, the linker must be able to resolve references to the functions and data contained by the .bpl file during linking. Such a reference is referred to as an external reference because it refers to something external to the current application. To resolve an external reference, the linker searches for an import record for the function called by the application. The import record is contained in the corresponding Borland Package Import (BPI) file (.bpi extension) for the Package. For every function that is exported from the Package (basically any function that is declared in a unit contained by the Package), there is an entry that states the internal name of the function and the name of the module that contains the function. In this case that is the name of the Package’s BPL file (more information than this is presented, but it is not relevant to this discussion). This information is copied by the linker to the application’s executable file. This creates a dynamic link to the function that will be resolved by Windows each time the application is executed. It does this by searching all the files on the system path (for example, files in the Windows system directory) for the file named by the import record when the application is loaded into memory. If it finds the required BPL file, that also is loaded into memory. The external reference is then referenced to the correct location within the BPL file. If the required BPL is already loaded into memory, then all the better. The overhead for this operation is not incurred, and the BPL is shared by the applications using it. The function or data can then be used by the application. It should be clear that the BPL and BPI files produced by a runtime Package are used to support dynamic linking of the code that the Package exports. The LIB file is used to support static linking of the code that the Package exports. Essentially, the LIB file contains the OBJ files of the units contained by the Package itself and is in fact an object library. When a function is required from the Package, the appropriate OBJ from the LIB file is copied to the target executable. Each such executable therefore has its own copy. Table 2.1 summarizes the purpose of the files produced by a Package when it is successfully built.
2 C++BUILDER PROJECTS
In Figure 2.5 we can see that three files are produced when a Package is built. The purpose of the BPL file depends on whether the Package is a designtime Package or a runtime Package. If it is a dual Package, the functionality of both Package types is available. With designtime Packages, the BPL file is used to install the Package into the IDE. This is done by selecting Install Packages from the Components menu and browsing for the designtime Package .bpl file. With runtime Packages, the BPL file is used specifically to allow applications to link dynamically to the functions and data that the Package contains at runtime.
04 9721 CH02
70
4.6.01
1:59 PM
Page 70
C++Builder 5 Essentials PART I
TABLE 2.1
Package Files Created on a Successful Build
Extension
Description
Type
Purpose
.bpl
Borland Package Library (BPL)
Dynamically linkable library
Contains executable code of the Package and exports the functions and data of the Package. A runtime library accessed by applica tions that are dynamically linked to it. A designtime library that can be installed into the IDE to make new components or editors available at designtime.
.bpi
.lib
Borland Import Library (BPI) Static Library File (LIB)
Import library
Object library
Contains import records for the functions and data exported by the corresponding BPL file required for dynamic linking to the BPL file. A static library containing the object files of the units contained by the Package. Used to statically link exported functions and data to a target application.
Table 2.1 shows that, in order to use a runtime BPL, the corresponding BPI file must be available at link time for the external references to the BPL to be resolved. Figure 2.6 illustrates the relationship between the files produced by a Package and an application that uses the Package. When you compile and link a project, you can choose whether the project is dynamically linked or statically linked to the Packages it requires. By default, dynamic linking is used. To change this setting for the project, uncheck the Build with Runtime Packages option on the Project Options, Packages page. It is also possible to choose units from a Package that you want to be statically linked to a given unit within a project. To do this, add the #pragma link “unitname” directive, generally near the top of the unit, where unitname is the name of the unit that you want to be statically linked to the unit within your project. This results in the linker copying the required object file from the Package’s .lib file.
Considerations when Using Packages For a class to be properly imported and exported from a Package, the PACKAGE macro must be used after the class keyword in the class definition, as shown in the following code:
04 9721 CH02
4.6.01
1:59 PM
Page 71
C++Builder Projects and More on the IDE CHAPTER 2
71
class PACKAGE TMyComponent : public TComponent { // Component class definition here. };
The PACKAGE macro must also be given in the declaration of the Register() function for the component. This is shown in the following code:
Linking
Runtime
Dynamically Link
Borland Package Import (BPI) External Reference
Import Record
Target Application
Borland Package Library (BPL) Dynamically Links to a Single Copy of the BPL
Target Application Statically Linked Executable Code
External Reference
Object file
Static Library File (LIB) Statically Link
FIGURE 2.6 The Package–application relationship.
Of course, this applies to component class definitions. If you use the Component Wizard to create the component, C++Builder will insert the PACKAGE macro for you. To ensure that functions and data are properly imported and exported from a unit contained in a Package, the #pragma package(smart_init) directive should be placed in the unit’s source file, typically after any #include statements but before any source code. Failing to do so will
2 C++BUILDER PROJECTS
namespace Newcomponent { void __fastcall PACKAGE Register() { TComponentClass classes[1] = {__classid(TMyComponent)}; RegisterComponents(“Samples”, classes, 0); } }
04 9721 CH02
72
4.6.01
1:59 PM
Page 72
C++Builder 5 Essentials PART I
not prevent the unit from compiling, but it will prevent the Package from statically linking. The purpose of the directive is to ensure that the packaged units are initialized in the order determined by their dependencies. The #pragma package(smart_init,weak) directive is also available. This is used when you do not want a particular unit to be contained in the BPL file. Instead, the unit is placed in the BPI file. When the unit is required, it is copied from the BPI file and statically linked to the target application. Such a unit is said to be weakly packaged and is used to eliminate conflicts among Packages that may depend on the same external library.
The C++Builder Runtime Packages C++Builder comes with a variety of runtime Packages that contain the core VCL as well as other libraries and components. These Packages are listed in Table 2.2, as are the units that are exported from each Package. TABLE 2.2
The C++Builder Runtime Packages
Runtime Package
Units Exported from Package
Runtime Functionality for:
dss50.bpl
Mxarrays, Mxbutton, Mxcommon, Mxconsts, Mxdb, Mxdcube, Mxdsql, Mxgraph, Mxgrid, Mxpbar, Mxpivsrc, Mxqedcom, Mxqparse, Mxstore, Mxtables
Decision Cube Components
ibevnt50.bpl
Ibconsts, Ibctrls, Ibevnts, Ibproc32
InterBase Events
inet50.bpl
Copyprsr, Httpapp, Webconst
inetdb50.bpl
Dbweb, Dsprod
Internet Components Internet Components
nmfast50.bpl
Nmconst, Nmdaytim, Nmecho, Nmextstr, Nmfngr, Nmftp, Nmhttp, Nmmsg, Nmnntp, Nmpop3, Nms_huge, Nms_stream, Nmsmtp, Nmstrm, Nmtime, Nmudp, Nmurl, Nmuue, Psock
FastNet Internet Components
qrpt50.bpl
Qr3const, Qrabout, Qrcomped, Qrctrls, Qrdatawz, Qrenved, Qrexpbld, Qrexport, Qrexpr, Qrexpred,
QReport Components
04 9721 CH02
4.6.01
1:59 PM
Page 73
C++Builder Projects and More on the IDE CHAPTER 2
TABLE 2.2
73
Continued
Runtime Package
Units Exported from Package
Runtime Functionality for:
Qrextra, Qrlabled, Qrlablwz, Qrprev, Qrprgres, Qrprnsu, Qrprntr, Qrwizard, Quickrpt Arrowcha, Brushdlg, Bubblech, Chart, Ganttch, Pendlg, Series, Tecanvas, Teeabout, Teeconst, Teefunci, Teengine, Teeprevi, Teeprocs, Teeshape, Teexport
TChart
teedb50.bpl
Dbchart
teeqr50.bpl
Qrtee
teeui50.bpl
Areaedit, Arrowedi, Axisincr, Axmaxmin, Baredit, Custedit, Dbeditch, Editchar, Flineedi, Ganttedi, Iedi3d, Iediaxis, Iedigene, Iedilege, Iedipage, Iedipane, Iediperi, Iediseri, Ieditcha, Iedititl, Iediwall, Pieedit, Shapeedi, Teegally, Teelisb, Teepoedi, Teestore
(Database) TChart (QReport) TChart (User Interface)
vcl50.bpl
Activex, Actnlist, Axctrls, Buttons, Classes, Clipbrd, Comconst, Comctrls, Commdlg, Comobj, Comstrs, Consts, Contnrs, Controls, Dialogs, Dsgnintf, Dsgnwnds, Editintf, Exptintf, Extctrls, Extdlgs,
2 C++BUILDER PROJECTS
tee50.bpl
TChart
Standard, Additional, System, Win32 and Dialog Components
04 9721 CH02
74
4.6.01
1:59 PM
Page 74
C++Builder 5 Essentials PART I
TABLE 2.2
Continued
Runtime Package
Units Exported from Package
Runtime Functionality for:
Fileintf, Flatsb, Forms, Graphics, Grids, Imglist, IniFiles, Istreams, Libhelp, Libintf, Mapi, Mask, Masks, Math, Menus, Mtx, Multimon, Oleconst, Olectnrs, Olectrls, Oleserver, Printers, Proxies, Registry, Scktcomp, Stdactns, Stdctrls, Stdvcl, Svcmgr, Syncobjs, Sysconst, System, Sysutils, Toolintf, Toolsapi, Toolwin, Typinfo, Vclcom, Virtin vclado50.bpl
Adoconst, Adodb, Adoint, Oledb
ADO Components
vclbde50.bpl
Bde, Bdeconst, Dbinpreq, Dbpwdlg, Dbtables, Smintf
vcldb50.bpl
Db, Dbactns, Dbcgrids, Dbcommon, Dbconsts, Dbctrls, Dbgrids, Dblogdlg, Dbolectl
Borland Database Engine Data Access and Data Controls Components
vcldbx50.bpl
Dblookup, Report, Rsconsts
TDBLookup Components
vclib50.bpl
Ib, Ibbatchmove, Ibblob, Ibcustomdataset, Ibdatabase, Ibdatabaseinfo, Ibevents, Ibexternals, Ibheader, Ibinstall, Ibintf, Ibquery, Ibservices, Ibsql, Ibsqlmonitor, Ibstoredproc, Ibtable, Ibupdatesql, Ibutils
InterBase Components
vclie50.bpl
Mshtml, Shdocvw
vcljpg50.bpl
Jconsts, Jpeg
Internet Explorer JPEG Functionality
04 9721 CH02
4.6.01
1:59 PM
Page 75
C++Builder Projects and More on the IDE CHAPTER 2
TABLE 2.2
75
Continued
Runtime Package
Units Exported from Package
Runtime Functionality for:
Corbacon, Corbaobj, Corbardm, Corbcnst, Corbastd, Databkr, Dbclient, Dsintf, Mconnect, Midas, Midascon, Midconst, Mtsrdm, Objbrkr, Orbpas, Provider, Sconnect
MIDAS Components
vclsmp50.bpl
Calender, Diroutln, Gauges, Spin
Sample Components
vclx50.bpl
Checklst, Colorgrd, Ddeman, Filectrl, Mplayer, Outline, Tabnotbk, Tabs
Win 3.1 and System Components
webmid50.bpl
Compprod, Miditems, Midprod, Scrptmgr, Pagitems, Wbmconst, Webcomp, Xmlbrokr
Internet Express Components
vclmid50.bpl
2
Using Tdump The tdump utility that comes with C++Builder (located in the Bin directory) can be used for examining the contents of BPL, BPI, and LIB files. In fact, any executable or library file can be examined with tdump. Open a DOS window and enter the following line, using the appropriate filenames in place of the names in italic text: tdump FileToBeExamined OutputFileName.dmp
When you press Enter, the file OutputFileName.dmp will contain a text representation of FileToBeExamined. This is a useful utility with which you should be familiar. To see only the exports from a BPL, use the -ee command-line option like this:
C++BUILDER PROJECTS
There are 22 Packages shown in Table 2.2, of which 19 are available in the Professional version of C++Builder. The ADO Package (vclado50.bpl), MIDAS Package (vclmid50.bpl), and Internet Express Package (webmid50.bpl) are available only in the Enterprise edition. This table can be used as a reference if you need to know which Package to add to your Requires section in a Package.
04 9721 CH02
76
4.6.01
1:59 PM
Page 76
C++Builder 5 Essentials PART I tdump –ee FileToBeExamined.bpl OutputFileName.dmp
To see only the units imported to a BPL, use the -em command line option like this: tdump –em FileToBeExamined.bpl OutputFileName.dmp
You can see the different options available simply by typing tdump and pressing the Enter key.
Introducing New IDE Features in C++Builder 5 C++Builder 5 contains many new features in the IDE. We’ll look at several of the most useful additions, including property categories and property images in the Object Inspector, the new Extensible Markup Language (XML) project file format, how form files are now saved in a text format, node-level project options, the project wide and source-code level To-Do list, and the new Console Wizard.
Property Categories in the Object Inspector In Chapter 1 we described how the IDE’s Object Inspector can be used to display and edit component properties and event handler functions. C++Builder 5 introduces the idea of property categories. All properties (which includes events) can now be arranged by category in the Object Inspector, as well as the normal alphabetical listing. The purpose of categories is to allow the logical grouping of related properties. A property may belong to more than one category, if appropriate. Additionally, it is possible to hide a property from the Object Inspector by hiding its category. This is referred to as filtering. Throughout the following sections, we will show you how to use property categories to group related properties in the Object Inspector window. The information applies equally to events. For information on how to register categories for properties in custom components, see the section “Registering Property Categories in Custom Components” in Chapter 10.
Using Property Categories By default the Object Inspector displays properties alphabetically. To view them by category, right-click on the working area of the Object Inspector and select Arrange, By Category. The property categories will now be displayed in the Object Inspector. These can be expanded or collapsed by clicking the + (expand) or - (collapse) icon (by default they are initially collapsed). This action is persistent: If a category is expanded and the properties are viewed by name before viewing them again by category, the category remains expanded. If another component is selected and it has properties in the same category, those will also be shown expanded. To filter which property categories are displayed in the Object Inspector, right-click again and select View. A category is checked or unchecked: Unchecked categories are hidden. Selecting View, All automatically checks all categories, selecting View, None unchecks all cat-
04 9721 CH02
4.6.01
1:59 PM
Page 77
C++Builder Projects and More on the IDE CHAPTER 2
77
egories (and therefore hides them), and selecting View, Toggle toggles the state of the categories. That is, checked categories become unchecked and vice versa. Changing the value of a property that occurs in more than one category results in the property’s value being changed consistently in all categories.
Using the Predefined Property Categories There are 13 predefined property (and event) categories, 12 of which are used by the VCL in C++Builder. These are described in Table 2.3, with the kind of property contained in each category and example properties. TABLE 2.3
Category Specification
Action
Contains properties that are managed by actions and whose behavior is related to runtime functionality. The Hint and Checked properties of TMenuItem are in this category. Contains properties that manage the data shown by a component. This category is not currently used by the VCL. It was originally used for the Text, EditMask, and Tag properties, but these can now be found in the Localizable, Localizable, and Miscellaneous categories, respectively. Contains properties whose behavior is related to database operations. The DatabaseName, MasterSource, and OnCalcFields properties of TTable are in this category. Contains properties that are related to drag-and-drop or docking operations. The OnDragOver and DockSite properties of TForm are in this category. Contains properties (and events) that are related to help, hint, or assistance operations. The OnHint and HelpContext properties of TStatusBar are in this category. Contains properties that are related to control input to the component. The OnKeyPress, OnClick, and Enabled properties of TForm are in this category. Contains properties that are related to the layout and visual display of a control at designtime. The OnResize and Width properties of TForm are in this category. Contains properties that are now obsolete. The Ctl3D and OldCreateOrder properties of TForm are in this category. Contains properties that are related to the linking of one component to another. The PopupMenu property of TForm and the DataSource property of TDBGrid are in this category.
Data
Database
Drag, Drop, and Docking Help and Hints
Layout
Legacy Linkage
C++BUILDER PROJECTS
Category Name
Input
2
Property Categories in C++Builder
04 9721 CH02
78
4.6.01
1:59 PM
Page 78
C++Builder 5 Essentials PART I
TABLE 2.3
Continued
Category Name
Category Specification
Locale
Contains properties that are related to international locales or compliance with international locale operating systems. The BiDiMode and ParentBiDiMode properties of TForm are in this category. Contains properties that are subject to possible change, depending on where the application is deployed. The BiDiMode, Hint, and Font properties of TForm are in this category. Contains properties that have not been categorized, do not fit into any category, or do not require categorization. The Tag and Name properties of TForm are in this category. Contains properties that are related to the layout and visual display of the control at runtime. The BorderStyle, Color, and Width prop erties of TForm are in this category.
Localizable
Miscellaneous
Visual
The table of categories is a useful indication of how categories are used by the VCL. A real appreciation of which properties can be found in which category will be gained only through a continued use of categories in the Object Inspector.
Images in Drop-Down Lists in the Object Inspector C++Builder 5 extends the TPropertyEditor class to include six new functions (see Chapter 10 for more information) that support the rendering of images in drop-down lists in the Object Inspector. This allows the Object Inspector to present a more intuitive interface for suitable properties. Property editors that overload these functions are shown in Table 2.4, along with VCL properties that are registered to use them. Properties that are registered to use these property editors will display the appropriate images associated with each property value. TABLE 2.4
Property Editors with Built-In Support for Images
Property Editor Class
VCL Property
TBrushStyleProperty
TBrush::Style
TColorProperty
TColor
TCursorProperty
TCursor
TFontNameProperty
TFont::Name
TPenStyleProperty
TPen::Style
TComponentImageIndexPropertyEditor
TImageIndex
TListViewColumnImageIndexPropertyEditor
TListColumn:: ImageIndex
04 9721 CH02
4.18.01
3:39 PM
Page 79
C++Builder Projects and More on the IDE CHAPTER 2
TABLE 2.4
79
Continued
Property Editor Class
VCL Property
TMenuItemImageIndexPropertyEditor
TMenuItem:: ImageIndex
TPersistentImageIndexPropertyEditor
TImageIndex
Properties registered using the TComponentImageIndexPropertyEditor, TListViewColumnImageIndexPropertyEditor, TMenuItemImageIndexPropertyEditor,
and property editors will show images only when the associated property of type TImageList is set to a TCustomImageList-descendant component containing the required images. TPersistentImageIndexPropertyEditor
The TComponentImageIndexPropertyEditor is for TImageIndex properties in components, (descendants of TComponent), with a parent component that has a TCustomImageList* with the name Images. This property editor will be used for custom components that meet these criteria. If a different name is required for the TCustomImageList* property in the parent component, a new property editor must be created that is derived from this one. Two things make this impractical. First, it is not possible to include the header of the $(BCB)\Include\Vcl\stdreg.hpp file where these four TImageIndex property editors are declared. This is because of missing header files included in the unit. Second, the rendering code is not correct for large images and is incorrectly offset. A better approach is to override this property editor, as is shown in the “A Generalized Solution for ImageIndex Properties” section in Chapter 10. The TListViewColumnImageIndexPropertyEditor and TMenuItemImageIndexPropertyEditor property editors are for TImageIndex properties with a parent component that has a TCustomImageList with the name SmallImages. The TPersistentImageIndexPropertyEditor is for TImageIndex properties in classes that are descendants of TPersistent (but not TComponent) with a parent component that has a TCustomImageList* property with the name Images. This property editor will be used for classes that meet these criteria. Again, if a different name is required for the TCustomImageList* property in the parent component, a new property editor must be created that is derived from this one. The best approach is to override this property editor as shown in the “A Generalized Solution for ImageIndex Properties” section in Chapter 10.
2 C++BUILDER PROJECTS
By default the global variable FontNamePropertyDisplayFontNames ($(BCB)\Include\ is set to false and font names are not shown in the Object Inspector using the actual font style of the font, rather the default MS Sans Serif font is used. This was done because the rendering of such images can be slow on low-end machines or those with many fonts installed. This time delay is incurred only the first time the property is displayed, so on most machines it is acceptable. To enable the images this variable must be set to true. Setting FontNamePropertyDisplayFontNames to true is a non-trivial exercise requiring the use of the Open Tools API. An alternative solution is to install a property editor that overrides TFontNameProperty. This approach is shown in Chapter 10.
Vcl\dsgnintf.hpp)
04 9721 CH02
80
4.6.01
1:59 PM
Page 80
C++Builder 5 Essentials PART I
Figure 2.7 shows how the ImageIndex property of TMenuItem can be used in conjunction with a TImageList component such that images contained in TImageList are displayed in the dropdown list of this property. To make the image list available, the Images property in the TMainMenu component must be set to (in this case) ImageList1.
FIGURE 2.7 ImageIndex
images in a TMenuItem component.
Figure 2.8 illustrates several property editors that display images in the Object Inspector using a TShape component, added as an example to the form in Figure 2.7. For more information on how to use drop-down list images in custom components, refer to the relevant section in Chapter 10, which also displays a class hierarchy for TPropertyEditor derived classes.
The XML Project File Format In C++Builder 5, project files (*.bpr and *.bpk) have changed from a Makefile format to the Extensible Markup Language (XML) format. You can view and edit the new XML project file in the IDE using Project, Edit Option Source. In previous versions of C++Builder, select Project, View Makefile. For compatibility with existing projects, the Makefile format can be formatted using a template file and exported. Simply select Project, Export Makefile. Alternatively, you can select Export Makefile for the particular project node from the context menu in the Project Manager. You can also export the Makefile using the BPR2MAK.EXE command-line tool.
04 9721 CH02
4.6.01
1:59 PM
Page 81
C++Builder Projects and More on the IDE CHAPTER 2
81
2 C++BUILDER PROJECTS
FIGURE 2.8 Drop-down list images in a TShape component.
When an existing project in the Makefile format is loaded into C++Builder 5, the project file format is automatically changed to the new XML format. A dialog box appears to inform you of this conversion. Listing 2.4 is a simplified version of the project file for the Doodle example program that shipped with C++Builder 4. It is in the original Makefile format. Listing 2.5 shows the same thing in the new XML format as it ships with C++Builder 5. Both have been greatly simplified for illustration purposes and are not working project files. LISTING 2.4
The Simplified Doodle Project File in C++Builder 4 Makefile Format
PROJECT = doodle.exe OBJFILES = doodle.obj main.obj palette.obj CFLAG1 = -I$(BCB)\include;$(BCB)\include\vcl -Od -Hc -H=$(BCB)\lib\vcl40.csm \ ➥-w -Ve -r- -k -y -v -vi- -D$(SYSDEFINES);$(USERDEFINES) -c -b- -w-par \ -w-inl -Vx -tW [Version Info] MajorVer=1 MinorVer=0
04 9721 CH02
82
4.6.01
1:59 PM
Page 82
C++Builder 5 Essentials PART I
LISTING 2.5
The Simplified Doodle Project File in C++Builder 5 XML Format
<MACROS> [Version Info] MajorVer=1 MinorVer=0
To most people it doesn’t matter whether the project file is in Makefile or XML format. The project file is built automatically according to the units that make up the project and the settings in the Project, Project Options dialog. If you use the MAKE command-line utility to compile your projects, you will need to export the project file as a Makefile in order to keep using the MAKE utility.
Forms—Save as Text This new feature of C++Builder version 5 saves forms as text rather than in binary form, as in previous versions. This is a default option, however, so forms may be saved as binary if so desired. Right-click on any project form to get the context menu. The Text DFM option is checked by default, as shown in Figure 2.9. When the form unit or project is saved, the form will be stored as plain text in its DFM file. An example text DFM file is shown in Listing 2.6. LISTING 2.6
An Example DFM File Saved as Text
object Form1: TForm1 Left = 192 Top = 107 Width = 311 Height = 158 Caption = ‘Text Form’ Color = clBtnFace Font.Charset = DEFAULT_CHARSET
04 9721 CH02
4.6.01
1:59 PM
Page 83
C++Builder Projects and More on the IDE CHAPTER 2
LISTING 2.6
83
Continued
Unchecking the Text DFM option of a form will cause the form to be saved as binary. It’s possible to make this the default for all new forms by unchecking the New Forms as Text option on the Preferences tab of the Environment Options dialog box, shown in Figure 2.10. This is reached by selecting Tools, Environment Options from the main C++Builder menu. Two example projects are provided in the TextForms folder on the CD-ROM that accompanies this book. FormText.bpr uses the Text DFM option to save the form as text. FormBinary.bpr does not use the Text DFM option and saves the form in binary format.
The Node-Level Options With the new Node-Level Options feature, you can override some of the project options for specific nodes (such as source files) of the project. There is a set of global project options and there also are local options for each of the nodes in the project, which default to the same as the global options.
2 C++BUILDER PROJECTS
Font.Color = clWindowText Font.Height = -11 Font.Name = ‘MS Sans Serif’ Font.Style = [] OldCreateOrder = False PixelsPerInch = 96 TextHeight = 13 object Label1: TLabel Left = 13 Top = 24 Width = 277 Height = 20 Caption = ‘This form is saved as text (default)’ Font.Charset = DEFAULT_CHARSET Font.Color = clWindowText Font.Height = -16 Font.Name = ‘MS Sans Serif’ Font.Style = [fsBold] ParentFont = False end object Button1: TButton Left = 114 Top = 72 Width = 75 Height = 25 Caption = ‘OK’ TabOrder = 0 OnClick = Button1Click end end
04 9721 CH02
84
4.6.01
1:59 PM
Page 84
C++Builder 5 Essentials PART I
FIGURE 2.9 The Text DFM (save as text) option on a form’s context menu.
FIGURE 2.10 The Preferences tab of the Environment Options dialog box.
Setting Global and Node-Level Options The global options can be set in the Project Options dialog, accessible from the Project, Options menu item. They are similar in appearance and function to the project options in previous versions of C++Builder. Options set here become the default for all nodes in the project.
04 9721 CH02
4.6.01
1:59 PM
Page 85
C++Builder Projects and More on the IDE CHAPTER 2
85
We’ll take a look at how this can be used with the Doodle example application that is installed with C++Builder 5. Let’s assume that we want to disable code optimization by default for all units in the project, but that we want to enable speed optimization for the main.cpp unit. The global Project Options dialog for the Doodle application with code optimization disabled by default is shown in Figure 2.11.
2 C++BUILDER PROJECTS
FIGURE 2.11 The global Project Options dialog for the Doodle application with code optimization disabled.
To override the default project options, you can set local options for a particular node through the Local Options dialog. This is accessible via the context menu for the node in the Project Manager. Figure 2.12 shows the Project Manager for the Doodle application, along with the context menu for the main.cpp node. The Local Options menu item is selected.
FIGURE 2.12 The Project Manager and Local Options context menu item for the main.cpp node of the Doodle application.
The Local Options dialog for this node is shown in Figure 2.13 with speed optimization enabled, thus overriding the default project option. Notice that, when you set local settings,
04 9721 CH02
86
4.6.01
1:59 PM
Page 86
C++Builder 5 Essentials PART I
they are highlighted with a different color in the dialog to indicate that they override the default project settings.
FIGURE 2.13 The Local Options dialog and settings for the main.cpp node.
Once a node’s settings are overridden in the Local Options dialog, that node is marked in the Project Manager with a red tick. Figure 2.14 shows how the main.cpp node is marked to indicate that some of the settings have been overridden.
FIGURE 2.14 The main.cpp node is marked to indicate settings have been overridden.
Reverting Node-Level Options To revert a specific locally set option to the project default, select Revert from the context menu of the option in question. To revert all locally set options on a particular page of the Project Options dialog, select Revert from the context menu of the tab. To revert all locally set options for the entire node, select Revert All from the context menu of the Right Click to Revert label. When you’re done, click OK.
04 9721 CH02
4.6.01
1:59 PM
Page 87
C++Builder Projects and More on the IDE CHAPTER 2
87
Uses for Node-Level Options The capability to override project options on a node-by-node basis allows you greater flexibility in the way that the project is built. You probably won’t need to use this feature very often, but it can be valuable in particular circumstances. Some likely instances in which you would override the default project options include the following: • To set size optimization as the default for your project, except for certain speed-critical units set to use speed optimization. • To use a different version of an include file with a particular unit by setting a different include path. • To disable particular warnings for a unit to avoid warning messages for code that is valid. • To use a different C++ language compliance for a unit that was supplied or developed according to a different standard. These are just some of the possible examples. There are undoubtedly many more cases that require node-level options override.
The New To-Do List A great enhancementin C++Builder 5 is the To-Do List. A to-do item can be added globally to the project or locally within your code to associate the item with a particular unit or section of code. A to-do list is an essential item for every programmer. Just about every project has some form of to-do list, whether it is part of the project management software or handwritten. The new To-Do List feature in C++Builder 5 brings that right into the code, making it easier for you to document a task in the first place and faster to find it later on. The Crozzle project (discussed in more detail in Chapter 6, “Compiling and Optimizing Your Application”) will be used to demonstrate the features of the To-Do List in the following examples. You can find it in the folder for Chapter 6 on the CD-ROM that accompanies this book. To-do items can be assigned a Priority (from 0 to 5), an Owner (a person or a group, as appropriate), and a Category. This helps in the overall management of the list, which can grow to a considerable number of items in even the most modest project.
The To-Do List View The To-Do List view is accessed from the View, To-Do List menu item in the C++Builder IDE. It lists three types of to-do items. Global items are shown in normal text. Local items in the open and active unit are shown in bold, and those in other units are shown in gray. The module name for local to-do items is shown in the To-Do List view.
C++BUILDER PROJECTS
• To use special conditional defines to modify the behavior of a unit.
2
04 9721 CH02
88
4.6.01
1:59 PM
Page 88
C++Builder 5 Essentials PART I
Figure 2.15 shows the To-Do List view for the Crozzle project, displaying several list items. In this section we will look at general item management through the use of the To-Do List view. The specific details and use of global and to-do items in particular are shown in following sections.
FIGURE 2.15 Crozzle project to-do list items displayed in the To-Do List view.
In the To-Do List view, most tasks are performed through the context menu. You can add global items, delete and edit any item, sort items on any field, and filter them by Category, Owner, Type, and Status. The to-do list can be copied to the Clipboard as text or to an HTML table for use in other documentation or software (for example, paste it into your project development intranet Web page). The HTML table properties are configurable from the Table Properties context menu item. To mark a to-do item as complete, simply check its Status check box. It will remain in the list until deleted.
Global To-Do List Items Global to-do items are stored in the file ProjectName.todo, which is automatically created and added to your project when a global to-do item is added. Examples of global items include • Milestone date reminders for a project • A list of features to be implemented • A list of features to add in the next version • Bugs that have not yet been tracked to a specific piece of code If you load the CrozzleProj.todo file of the Crozzle project into a text editor (such as Notepad), you will see a list of to-do list items enclosed in braces ({}). They contain various fields and a description. These form the global to-do list for the project. Use the To-Do List view in the C++Builder IDE to manage them.
04 9721 CH02
4.6.01
1:59 PM
Page 89
C++Builder Projects and More on the IDE CHAPTER 2
89
To add a global list item to the project, right-click and select Add from the context menu in the To-Do List view. Enter appropriate values for the description, priority, owner, and category and click OK. All previously used values for Owner and Category in the current project can be selected from the drop-down lists.
Local To-Do List Items A local to-do item appears as a special comment within your code. It is automatically added to your source code when you add a method to an object using the Add Method dialog from the context menu of the Class Explorer.
• A bug note • A note that a piece of code needs improvements • To mark code that looks suspicious • To help find your place later • To indicate changes that need to be made to user manuals as the result of a code change Local to-do list items are simply declared as C++ style comments within your code in a particular format. They are similar in appearance to the global to-do list items in the projectname.todo file. Listing 2.7 shows a portion of the Crozzle project code that contains a local to-do list item. LISTING 2.7
A Local To-Do List Item in CrozzleSolve.cpp
//--------------------------------------------------------------------------void __fastcall TCrozzleForm::HelpAboutItemClick(TObject *Sender) { TAboutForm *AboutForm = new TAboutForm(Application); /* TODO 5 -oJarrod -cEnhancement : Position the about box in centre of ➥crozzle window. */ AboutForm->ShowModal(); }
The comment is constructed with a number of fields. Some are optional and are not included if the value was not given. A priority of zero is not shown in the comment. The comment format is /* status [priority] [-o owner] [-c category ] :
description
*/
2 C++BUILDER PROJECTS
You can also add to-do list items manually. When doing so, you specify where in the code they are to be placed. They can be added just about anywhere within the code (including header files) except at the top of a unit above the include file declarations. Some practical uses for local to-do items include
04 9721 CH02
90
4.6.01
1:59 PM
Page 90
C++Builder 5 Essentials PART I
LISTING 2.7
Continued
or // status [priority] [-o owner] [-c category] : description
The easiest way to add a local to-do item is to select Add To-Do Item from the context menu by right-clicking in the appropriate place in the Code Editor or by pressing Shift+Ctrl+T to insert an item at the cursor. Items can also be entered manually by typing them into the Code Editor in the correct format (the code is continually parsed, and they will be picked up automatically).
CAUTION Because the text from the to-do item description is entered into a comment within your code, make sure that you don’t use the /* or */ character combinations in the description, Doing so will cause the To-Do List view, Class Explorer, Code Insight, and the compiler to interpret the comment incorrectly.
From the To-Do List view, you can jump straight to the code of a local to-do item by doubleclicking it or selecting Open from the context menu. When a local item is marked as Complete (through the To-Do List view), the comment remains in the code. The status word TODO in the comment is changed to DONE. You might want to leave completed items in the code to keep a history of them. To delete a pending or completed to-do item, either select Delete from the context menu in the To-Do List view or delete the comment in the code. Experiment with the To-Do List feature and make a point of using it diligently. Don’t let the list get out of date!
The Console Wizard Several new applications wizards are included with C++Builder version 5, one of these being the Console Wizard. This wizard provides a few simple options to make it easier to build console applications, which are Win32 applications without the usual graphical user interface.
Starting the Console Wizard The Console Wizard, as with all application wizards, may be started by selecting File, New from the C++Builder main menu. Select the Console Wizard icon from the New Items form, as shown in Figure 2.16.
04 9721 CH02
4.6.01
1:59 PM
Page 91
C++Builder Projects and More on the IDE CHAPTER 2
91
2 The new application Console Wizard icon.
The options dialog will then be displayed. These options are • Source Type Specifies whether the source language will be C or C++. • Use VCL Allows use of VCL components. This option is available only if C++ is specified as the source language. • Multi Threaded Specifies multiple execution threads. This option is automatically selected if Use VCL is checked. • Console Application Checking this option will cause a console window to be created for the application. It is also possible to specify the location of an existing source code file, which will then be automatically loaded. The options dialog is shown in Figure 2.17.
FIGURE 2.17 The Console Wizard options dialog.
When the options are set and you click OK, a skeleton function is created in the Code Editor. For example, checking only the C++ and Console Application options causes the main() skeleton function, shown in Listing 2.8, to be created.
C++BUILDER PROJECTS
FIGURE 2.16
04 9721 CH02
92
4.6.01
1:59 PM
Page 92
C++Builder 5 Essentials PART I
LISTING 2.8
Skeleton Code for a Console Application
//------------------------------------------------------------#pragma hdrstop //------------------------------------------------------------#pragma argsused int main(int argc, char* argv[]) { return 0; } //-------------------------------------------------------------
A Simple Console Application This brief example uses the C Source Type option with Console Application checked to generate a console window. Adding the code to the main() skeleton function as shown in Listing 2.9 will generate the output shown in Figure 2.18 when run. You can find the complete project, with the project filename MyConsole.bpr, in the Console folder on the CD-ROM that accompanies this book. LISTING 2.9
The Simple Console Application Code in MyConsoleCode.c
//------------------------------------------------------------#pragma hdrstop #include <stdio.h> #include //------------------------------------------------------------#pragma argsused int main(int argc, char* argv[]) { printf(“Hello World!\n”); getch(); return 0; } //-------------------------------------------------------------
04 9721 CH02
4.6.01
1:59 PM
Page 93
C++Builder Projects and More on the IDE CHAPTER 2
93
2 Simple console application output.
Summary In this chapter we have looked at C++Builder projects in detail, learned how to reuse projects and other program elements using the Object Repository, and gained an understanding of what Packages are and how they can be used. We also looked at several new IDE features in C++Builder 5. The IDE is very powerful and is a great aid to productivity, and the features explained in this chapter will make development easier for you. We’ll make use of some of these features in later chapters.
C++BUILDER PROJECTS
FIGURE 2.18
04 9721 CH02
4.6.01
1:59 PM
Page 94
05 9721 CH03
4.6.01
1:59 PM
Page 95
Programming in C++Builder Jamie Allsop
IN THIS CHAPTER • Coding Style to Improve Readability • Better Programming Practices in C++Builder • Further Reading
CHAPTER
3
05 9721 CH03
96
4.6.01
1:59 PM
Page 96
C++Builder 5 Essentials PART I
This chapter introduces important concepts concerned with how code is written in C++Builder. The first section concentrates on how the readability of code may be improved. Optimizing the readability of code is very important. More readable code is easier to understand and maintain, and this can have a big effect on the cost of a software project. It is more than just making code look pretty on a page; it is about augmenting the code’s description such that its purpose, intent, and behavior are adequately reflected. Adopting a coding style and applying it consistently is probably the easiest way to achieve more readable code. However, some styles offer greater improvement than others, and this section looks at a variety of approaches to several considerations in an effort to give the reader some insight into which styles they should adopt. More importantly, it offers suggestions as to why certain styles are possibly more effective than others as well as warnings on the application of certain styles. Some techniques in moderation are very effective but when overused will decrease readability. Situations such as this are highlighted. The fundamental elements of coding style are examined in turn, and guidelines are presented on how each element can affect readability, along with suggestions on how each element can be used to best effect. Where appropriate, effective use of the IDE is also covered. The second section covers a variety of topics concerning the writing of C++ code in C++Builder applications. A wide range of topics is covered, from the use of new and delete to the use of const in programs. The main purpose of the section is to highlight areas of coding that are often misunderstood or misused. Often, certain concepts are not fully appreciated, particularly by programmers whose background is not in C++. However, the main target audience is those whose background is in C++. They will find explanations of specific issues concerning the use of C++ in C++Builder and should therefore benefit from the topics covered. Some topics begin with more straightforward material before moving the discussion to advanced concepts. Also, many of the topics address issues that arise as a result of the Object Pascal heritage of the VCL (Visual Component Library). Finally, the last section, “Further Reading,” lists the references that appear throughout the chapter, along with a brief description of the reference itself. You are encouraged to seek out these references; reading them should prove very beneficial.
Coding Style to Improve Readability This section looks at some of the issues in improving the readability of code and offers possible methods of achieving this. Regardless of which styles and methods are chosen, the one thing that should be remembered is that you must be consistent. Consistency is very important (note that code in this section is written in different styles to illustrate points in the text).
05 9721 CH03
4.6.01
1:59 PM
Page 97
Programming in C++Builder CHAPTER 3
97
The Use of Short and Simple Code It may be obvious, but always try to keep any given block of code short and simple. This achieves two things. First, it means that your code is ultimately the culmination of many smaller pieces of code, each of which serves a specific and understandable role. This means that at different parts of the code the complexity of the code is governed only by the level of abstraction, not by the amount of code present. Consider the two functions in Listing 3.1. LISTING 3.1
Code Complexity and Level of Abstraction
#include double GetMaximumValue(const std::vector<double>& Vector) throw(std::out_of_range) { double Maximum = Vector.at(0);
return Maximum; } void NormalizeVector(std::vector<double>& Vector) { if(!Vector.empty()) { double Maximum = GetMaximumValue(Vector); for(int i=0; i
Both of the above functions are similar in terms of the complexity of the code that they contain, but the second function, NormalizeVector, performs in total a more complex task, because the level of abstraction is higher.
3 PROGRAMMING IN C++BUILDER
for(int i=0; i Maximum) { Maximum = Vector[i]; } }
05 9721 CH03
98
4.6.01
1:59 PM
Page 98
C++Builder 5 Essentials PART I
TIP Use the pre-increment operator instead of the post-increment operator—for example, in Listing 3.1, ++i is used in preference to i++. Using either of the increment operators will increment i, but the post-increment version will return the old value of i. Since this is not required, the extra processing time is wasted. Typically, the postincrement operator is implemented in terms of the pre-increment operator. The pre-increment operator is therefore faster than the post-increment operator. For built-in types such as int, there is little difference in speed, but for user-defined types this may not be the case. Regardless, if the post-increment operator is repeatedly used unnecessarily, there will be a cost in terms of performance.
Second, it means that when you are reading code you are never too far away from local variable declarations and function parameters (which contain type information). To this end, if you find yourself writing large pieces of code that perform several tasks, consider how the code could be separated into smaller conceptual blocks and rewritten accordingly.
The Use of Code Layout The easiest way to improve the layout of your code is to make sure that braces ({}) are placed on their own line and that matching pairs line up. Code inside braces should then be indented by a predetermined amount that is used consistently throughout the program. Typically, two to four spaces are used as a suitable indent, though some use more and some use only one. (Beware of too many spaces; this can actually degrade readability.)
TIP Make sure the Use Tab Character setting on the General tab in Tools, Editor Options is unchecked. This ensures that spaces are inserted for tabs. In general, avoid using Tab; use spaces instead.
Why is this so helpful? First, it allows fast visual scanning of the code. The code can be broken quickly into its constituent functional blocks, and each block’s nature can be seen from the line starting the block. Second, the scope of the code is very clear. It is obvious which variables are in or out of scope at any given time, and this can be helpful in tracking down problem code. This is an important feature of this approach. Remember that the scope of any given block includes the block header statement (such as a for statement or a function header), and the functional part of the block is the code contained by the braces. Aligning the braces with the block header statement and indenting the functional code show this logical relationship explicitly.
05 9721 CH03
4.6.01
1:59 PM
Page 99
Programming in C++Builder CHAPTER 3
99
The reason this layout style is so effective is that it is easier to match a pair of braces than it is to match an end brace with a keyword (or other permutations), due to the lack of symbolic similarity. It is also easy to maintain, because each opening brace must have a corresponding ending brace in the same column.
TIP The IDE allows you to indent and unindent selected blocks of code using, respectively, CTRL+SHIFT+I and CTRL+SHIFT+U. The number of spaces that the editor indents or unindents the selected code is determined by the value of the Block indent setting on the General tab in Tools, Editor Options. Setting this value to 1 (one) offers the greatest flexibility.
When code is laid out as previously described—braces on their own line, matching pairs of braces lined up, and code within the braces indented—it can be read easily. Loop constructs can be marked as blocks, and nested constructs become very clear. No room is left for ambiguity. One instance in which this can be particularly useful is in the use of nested if-else statements. The following code is unclear: #include // We have : int A <= int B <= int C if(A + B > C) if((A==B) || (B==C)) if((A==B) && (B==C)) std::cout << “This is an EQUILATERAL triangle”; else if( (A*A + B*B) == C*C ) std::cout << “This is a RIGHT-ANGLED ISOCELES triangle”; else std::cout << “This is an ISOCELES triangle”; else if( (A*A + B*B) == C*C )std::cout << “This is a RIGHT-ANGLED triangle”; else std::cout << “This is a TRIANGLE”; else std::cout << “This is NOT triangle”;
3 PROGRAMMING IN C++BUILDER
Indenting both the braces and the code contained in them together is not as effective, because the braces are hard to pick out in the code. For single blocks of code this is not such a problem, but for nested blocks it can become confusing. That said, some still prefer this approach. For an alternative discussion of this, please refer to A Practical Handbook of Software Construction by McConnell, 1993, p. 399. Be aware that most of the discussion presented in the book refers to languages that use keywords to show control block structures, such as begin and end, and the considerations involved are therefore somewhat different, though the distinction is not considered by the text. Tread cautiously.
05 9721 CH03
100
4.6.01
1:59 PM
Page 100
C++Builder 5 Essentials PART I
Its meaning is straightforward when written as follows: #include // We have : int A <= int B <= int C if(A + B > C) { if((A==B) || (B==C)) { if((A==B) && (B==C)) { std::cout << “This is an EQUILATERAL triangle”; } else if( (A*A + B*B) == C*C ) { std::cout << “This is a RIGHT-ANGLED ISOCELES triangle”; } else { std::cout << “This is an ISOCELES triangle”; } } else if( (A*A + B*B) == C*C ) { std::cout << “This is a RIGHT-ANGLED ISOCELES triangle”; } else std::cout << “This is a TRIANGLE”; } else std::cout << “This is NOT triangle”;
Always consider if there is a better, clearer way to write code, especially if you find yourself writing large nested if and if-else statements. If you are writing a large if-else block, consider replacing it with a switch statement. This may not always be possible. In the case of large nested if statements, try restructuring the code into consecutive if-else statements. In a similar vein, try to keep lines of code short. This makes it easier to read in the editor window and also makes it easier to print out.
TIP Often when code is printed, some code lines are too long for the page onto which they are printed. When this occurs, one of two things happens: The lines are wrapped to the start of the next line or the lines are simply truncated. Both are unsatisfactory and degrade the readability of the code.
05 9721 CH03
4.6.01
1:59 PM
Page 101
Programming in C++Builder CHAPTER 3
101
The best way to prevent this is to ensure that excessively long lines of code either are avoided or that they are carefully broken to multiple lines. When you are writing code in the Code Editor, the right margin can be used as a guide to the width of the printable page that you use. Change the right margin setting on the Display tab in the Tools, Editor Options menu so that the value represents the absolute printable right margin. In other words, set it so that characters that appear after this margin either are not printed or are wrapped to the next line (if Wrap Lines is checked in the File, Print menu). This will depend on the page size used and the value of the left margin setting (also in the File, Print menu). For A4 paper and a left margin setting of 0, the right margin should be set to 94. This means that code lines that extend past this line will not be printed as they appear on the screen. To ensure that the right margin is visible in the Code Editor, make sure that the Visible Right Margin setting on the Display tab in the Tools, Editor Options menu is also checked.
For heavily nested loops or selection constructs, decrease your indent size if it is large or redesign the code so that some of the work is carried out by functions. switch
statements can be written differently. For example
switch(Key) { case ‘a’ : // a very long line of code that disappears ... break; case ‘b’ : // another very long piece of code ... break; default : // Value not required – default processing break; }
This can be rewritten as switch(Key) { case ‘a’ : // a very long line of code that can now all be seen break; case ‘b’
3 PROGRAMMING IN C++BUILDER
Common reasons why code lines can become excessively long include heavily nested loops or selection constructs, use of switch statements with complex code inside, trying to write for and if statements on the same line, long function parameter lists, long Boolean expressions inside if statements, and string concatenation using the + operator.
05 9721 CH03
102
4.6.01
1:59 PM
Page 102
C++Builder 5 Essentials PART I : // another very long piece of code that can also be seen break; default : // Value not required – default processing break; }
With for and if statements all on one line, place the code executable part of the statement on a separate line. For example for(int i=0; i<10; ++i) // long code that disappears ...
This can be replaced by the following: for(int i=0; i<10; ++i) { // long piece of code that no longer disappears }
The if statement can be similarly written. For example if( Key == ‘a’ || Key == ‘A’ ) // long code that disappears ...
This can be replaced with if( Key == ‘a’ || Key == ‘A’ ) { // long piece of code that no longer disappears }
In fact, it is better practice to write such one-line statements in this way, because it allows the debugger to trace into the line of code that is to be executed. Long Boolean expressions inside if statements should be written on several lines, such as in the following: if(Key == VK_UP || Key == VK_DOWN || Key == VK_LEFT... { // Code here }
This is better written as follows: if(Key == || Key || Key || Key || Key || Key {
VK_UP == VK_DOWN == VK_LEFT == VK_RIGHT == VK_HOME == VK_END)
05 9721 CH03
4.6.01
1:59 PM
Page 103
Programming in C++Builder CHAPTER 3
103
// Code here }
This code raises an important point concerning the placement of the || or similar operator. The reason for placing it on the left side of each line is that we read from left to right. Placing it on the right makes the reading both slower and less natural, and it distorts the emphasis of the expression. Placing the operator on the right side of each line in the expression to show that there is more after the line is unnecessary, because people tend to read code by scanning blocks, not by reading individual lines as a computer does. Long function parameter lists can be dealt with similarly, by placing each parameter on a new line. For example void DrawBoxWithMessage(const AnsiString &Message, int...
This can be rewritten as shown in Listing 3.2. LISTING 3.2
Writing Long Function Parameter Lists
It is important to place the comma at the end of each line. Placing the comma at the start of each line makes the code more difficult to read, because you would not expect to encounter a comma in this position in normal written text. The comma is for the compiler to separate the parameters and has no other meaning; its use should not unduly confuse someone reading the program. Note that the positioning of the comma is in contrast to the previous discussion of operator placement. The same approach can be taken with long string concatenations: AnsiString FilePath = “”; AnsiString FileName = “TestFile”; FilePath = “C:\\RootDirectory” + “\\” + “Branch\\Leaf” + ...
This can be rewritten as shown in Listing 3.3. LISTING 3.3
Writing Long String Concatenations
AnsiString FilePath = “”; AnsiString FileName = “TestFile”; FilePath = “C:\\RootDirectory” + “\\”
3 PROGRAMMING IN C++BUILDER
void DrawBoxWithMessage(const AnsiString &Message, int Top, int Left, int Height, int Width);
05 9721 CH03
104
4.6.01
1:59 PM
Page 104
C++Builder 5 Essentials PART I
LISTING 3.3
Continued + “Branch\\Leaf” + FileName + ”.txt”;
The code in Listing 3.2 and Listing 3.3 is very clear, but it may not be very easy to maintain due to the amount of indentation required. For those who find adding lots of spaces difficult (some people really do!), an alternative approach is to use the standard indent for each of the following lines in such an expression. For example, if you are using a three-space indent, then the code from Listing 3.2 would become void DrawBoxWithMessage(const AnsiString &Message, int Top, int Left, int Height, int Width);
This degrades readability but results in code that is easier to maintain, a rather dubious tradeoff, but sometimes a reasonable one.
TIP You can save time writing code by using the code templates. These are accessed from the editor by pressing Ctrl+J and then using the up and down arrow keys or the mouse to select a template. However, remember that in order to maintain consistency with your own coding style and to get the best use of code templates, you should customize the templates that C++Builder provides. To edit code templates, go to Tools, Editor Options and select the Code Insight tab. Note that the | character is used to indicate where the cursor will be placed initially when the template is pasted into the editor. Code templates can also be edited manually in the $(BCB)\Bin\Bcb.dci file (where $(BCB) is the C++Builder 5 installation directory).
The Use of Sensible Naming One of the best ways to improve the readability of code is to use sensible naming for variables, types, and functions. Type names include those used for naming actual types; for example int is the type name for an integer, TFont is the type name for the VCL’s font class. Variable names are the names of variables that are declared to be of a specific type, for example, in the code int NumberOfPages; NumberOfPages
is the name of a variable of type int.
05 9721 CH03
4.6.01
1:59 PM
Page 105
Programming in C++Builder CHAPTER 3
105
Function names are given to functions to describe what they do. We’ll consider variable names first, though most of what is said about variable names applies equally to type names and function names.
Choosing Variable Names to Indicate Purpose Generally, you want to choose a name that reflects a variable’s nature and purpose. If possible, it should also suggest what type the variable is. For example, String EmployeeName; is better than String S;. When the variable pops up later in code, you will have no idea what S is for. For example, is it the number of pages in a book or a string representing a person’s name? You also won’t know what it is—for example, an int, a double, a String? EmployeeName is obvious: It is a variable that holds the name of an employee, and it is most likely a string. Using descriptive names such as this is easy to do and makes everyone’s life much easier when the code is read at a later date. Every time a new variable is declared, ask the question, “What is the variable’s purpose?” Summarize the answer to the question and you have a sensible variable name.
String String String String
EmployeeName; employee_name; Employee_Name; employeeName;
A disadvantage of using underscores is that variable names can quickly become very long. These are okay technically, but they start to make code look cluttered and also increase the symbolic appearance of variable names. Some suggest that all variable names should start with a lowercase letter, such as the employeeName example. This is often done to separate variable names from type names, which would typically start with a capital letter. Others start a variable name with a lowercase letter only when it is a temporary variable, such as a temp variable in a swap function. A compromise should be found so that a variable name is meaningful but also concise. That said, the meaningfulness of a variable name is most important.
Modifying Variable Names to Indicate Type In general, knowing the purpose of a variable is often more important to the understanding of a piece of code than knowing what type the variable is. However, there are times when you may want to remind yourself of the variable type because special rules might apply. A simple example to illustrate this is given in Listing 3.4.
3 PROGRAMMING IN C++BUILDER
When naming a variable, a word or short phrase is often used. Using a capital letter to start each word in the variable name is a popular method of making the name clear and easy to read. Others prefer all lowercase with underscores to separate words and, still others, a mixture of both. To illustrate, the previous declaration could be written as any of the following:
05 9721 CH03
106
4.6.01
1:59 PM
Page 106
C++Builder 5 Essentials PART I
LISTING 3.4
Illustrating the Need to Be Aware of a Variable’s Type
int Sum = 0; int* Numbers = new int[20]; for(int i=0; i<20; ++i) { Numbers[i] = i*i; Sum += Numbers[i]; } double Average = Sum/20; // Sum is an int, needs cast as a double
The answer to the code in Listing 3.4 should be 123.5, but the value in Average will be 123. This is because Sum is an int, and when you divide by 20 (treated as an int), you get an int result that is assigned to Average.
TIP Try to declare variables just before they are used; this helps ensure that variables are created only if they are actually needed. If code contains conditional statements (or throws an exception), it may be that some of the variables declared are not used. It is sensible not to incur the cost of creating and destroying such variables unless they are used. Be wary, though, of placing declarations inside loops, unless that is what is intended. It is also a good idea to initialize variables when they are declared. On a similar note, never mix pointer and non-pointer declarations on the same line. Doing so is confusing at best. It is preferable to have variables declared as Type VariableName;
Hence, a pointer to an int should be written as int* pointerToInt;
But if we write int* pointerToInt, isThisAPointerToInt;
then PointerToInt is a pointer to an int and isThisAPointerToInt is not a pointer to an int, it is an int. Actually, this is what the declaration is saying: int *pointerToInt, notPointerToInt;
This is still not clear, and the declaration is no longer written in the Type VariableName format. The solution is to write the declarations on separate lines. The ambiguity then disappears. int* pointerToInt = 0; int notPointerToInt;
05 9721 CH03
4.6.01
1:59 PM
Page 107
Programming in C++Builder CHAPTER 3
107
You should ensure that pointers are explicitly initialized either to NULL (0) or to some valid memory location. This prevents the accidental use of wild pointers (those that point to an undefined memory location).
To obtain the expected result of 123.5 for Average in Listing 3.4, the last line of the code snippet should be as follows: double Average = static_cast<double>(Sum)/20; // Performs as expected
This results in Sum being cast as a double before being divided by 20 (treated as a double). Average is now assigned the double value 123.5.
TIP Make sure you are familiar with the four types of C++ casts, and always use C++-style casting in preference to C-style casting. C++-style casts are more visible in code and give an indication of the nature of the cast taking place.
Sometimes type information may be required. One method of adding type information to a variable name is to use a letter (or letters) as a symbol at the start or at the end of each variable name. For example, you might use b for bool, s for a string, and so on. A problem with this approach is that type information can be added unnecessarily to too many different types of variables. The emphasis is then invariably placed on the type information and not on the variable’s purpose. Also, there are many more possible types for a variable than there are letters of the alphabet. As a result, such symbols can themselves become confusing and complex. An infamous example of such a convention is the Hungarian Notation commonly seen in Win32 API code.
NOTE The Hungarian Notation has its roots in Win API programming and advocates adding symbols to all variables to indicate their type. Since there aren’t enough letters for all types, oddities in the notation are common. For example, Boolean variables are pre-
PROGRAMMING IN C++BUILDER
This example is somewhat trivial, and adding type information to the variable name would be a bit like using a sledgehammer to crack a nut. A more sensible solution is probably to declare Sum as a double.
3
05 9721 CH03
108
4.6.01
1:59 PM
Page 108
C++Builder 5 Essentials PART I
fixed with an f, strings with an sz, pointers with p, and so on. A complete list is not appropriate here. The notation is infamous because many feel it creates more problems than it solves. These arise mostly from inconsistencies (such as the variable wParam being a 32-bit unsigned integer, not a 16-bit unsigned integer as the prefix implies) and names that are difficult to read. A perusal of the Win32 API help files should reveal some examples of the notation. Heavily typed notations are dangerous because they place the emphasis of a variable name on the variable’s type, which often does not tell you much about the variable.
When reading such code, it is not always easy for the reader to mentally strip away the type codes, and this can decrease the code’s overall readability. If you want prefixed (or even appended) type symbols, a compromise is to restrict the use of added symbols to only a few specific types.
Modifying Variable Names to Indicate Characteristics or Restrictions A variable’s name can also be used to convey information regarding some characteristic that a variable may have or to point out some restriction that may be applicable. It is important to know when a variable is a pointer, because pointers can easily wreak havoc in a program. For example, if you have a pointer to an int and accidentally add 5 to it without dereferencing it first, you have a problem. It is good practice to use a pointer only when no other type can be used, such as a reference (which are implicitly dereferenced). It is also sometimes important to know when a variable is static, when a variable is a class data member, or when a variable is a function parameter. Suitable symbols that could be prefixed would be p_ for a pointer, s_ for a static variable, d_ or m_ for a class data member, and a_ for a function parameter. (An a_ symbol is used to differentiate a function parameter from a pointer and should be read as “where the parameter a_x represents the argument passed to the function.” The use of a_ then becomes reasonable.) An underscore is often used to separate a prefix from the variable name proper. This makes it easier to strip away the prefix when reading the code. If a separating underscore is used with an information symbol, then it is possible to append the symbol to the end of the variable name. This has the advantage of allowing the variable name to be read more naturally. For example, when reading s_NumberOfObjects, you would probably say “this is a static variable that holds the number of objects,” whereas reading NumberOfObjects_s, you might say “this variable holds the number of objects and is static.” This places the emphasis on the purpose of the variable (to store the number of objects). Which you prefer is probably a matter of personal choice. A problem with all such symbols occurs when more than one is applicable; then the syntax is not so tidy. Solutions such as always prefixing p_ for pointers and appending the other symbols can solve most of these problems, but not all.
05 9721 CH03
4.6.01
1:59 PM
Page 109
Programming in C++Builder CHAPTER 3
109
Another common situation that often receives special attention is the naming of variables whose values do not change, in other words constants. Such variables are often named using all capital letters. When you declare variables of certain classes, it is often sensible to include the class name (without any prefixed letter, for example T or C, if it is present; this is explained shortly) as part of the variable name. This is often done by prefixing some additional information to the name, or it can be as crude as appending a number to the class name as the C++Builder IDE does, though generally a little more consideration should be applied. For example, consider the following variable declarations. TComboBox* CountryComboBox; TLabel* NameLabel; String BookTitle;
In the case of TComboBox and TLabel, it is appropriate to include the class name as part of the variable name. However, in the case of BookTitle, it is fairly obvious that it is a string, and adding the word String to the variable name perhaps does more harm than good.
Choosing Type Names As was mentioned earlier, the naming of types should be approached in a fashion similar to the naming of variables. However, some conventions need to be considered. For classes, convention says that if the class derives from TObject, then the class name should be prefixed with the letter T. This lets the user of the class know that it is a VCL-style class, and it is consistent with the naming of other VCL classes. This has a beneficial side effect. Variables declared of the class can use the class name without the prefix, making it obvious what the variable is. Non-VCL (that is, normal C++) classes can also use a prefix, but it is wise perhaps to use a prefix other than T, such as C to indicate that the normal C++ object model applies and reinforce that the class does not descend from TObject. This distinction can be important: VCL-style classes must be created dynamically; non-VCL classes do not have this restriction. The naming of other types, such as enums, Sets, structs, and unions, can be handled in a similar fashion. By convention, C++Builder prefixes a T to enumeration and Set names, though some may prefer not to follow this convention, which has no specific meaning. Avoid using an E as a prefix; C++Builder uses this for its exception classes.
3 PROGRAMMING IN C++BUILDER
Of special note in C++Builder is the naming of private member variables, which have a corresponding __property declaration. By convention, such variables are prefixed with the letter F (for Field). You should follow this convention and avoid using a capital F prefix for other purposes. The purpose of a prefix in this case is to allow the property name to be used unchanged (it is not necessary to think of a similar-sounding variant name).
05 9721 CH03
110
4.6.01
1:59 PM
Page 110
C++Builder 5 Essentials PART I
Because enums and Sets are commonly used in C++Builder, it is worth mentioning some points specifically related to their naming. A Set is a template class declared in $(BCB)\Include\VCL\sysset.h as template ➥ class RTL_DELPHIRETURN Set;
Ignoring RTL_DELPHIRETURN, which is present for VCL compatibility, we can see that a Set template takes three parameters: a type parameter and two range-bounding parameters. Hence, a Set could be declared as Set CapitalLetterMask;
If a Set is to be used more than once, a typedef is normally used to simplify its representation, as seen here: typedef Set TCapitalLetterMask; // Later in the code TCapitalLetterMask CapitalLetterMask; Sets
are often used to implement masks (as in this case), hence the use of the word Mask in the names used in the previous code. An enumeration is typically used to implement the contents of a Set. For example, the following definitions can be found in $(BCB)\Include\VCL\graphics.hpp:
enum TFontStyle { fsBold, fsItalic, fsUnderline, fsStrikeOut }; typedef Set TFontStyles;
Most enums used by the VCL are to facilitate the use of Sets. For convenience they are declared at file scope. Simply including the file allows easy access to the Set. This means that the potential for a name collision is high. To avoid such collisions, the “initials” of the enum name are prefixed to each of the values that the enum can take. This minimizes the chance of a name collision. This is good practice and should be used in your own code. For example, the initials of TFontStyle (excluding the T) are fs, which is prefixed to each of the enums. Another method that can be used to prevent name collisions is to place enums and typedefs inside the class definitions that use them. This means that such enums and typedefs, when called from outside the class, must be qualified by the class namespace. The same can be applied to const values. Using a typedef in certain situations (such as this one) can improve readability. A typedef can also improve readability in the declaration of function pointers (and particularly __closures, i.e. events, discussed in Chapter 9, “Creating Custom Components”). Beyond situations such as these, typedefs should be used sparingly because you are actually hiding the type of the variable. Using typedefs too much will result in confusion.
05 9721 CH03
4.6.01
1:59 PM
Page 111
Programming in C++Builder CHAPTER 3
111
Choosing Function Names Function names should be precise and describe what the function does. If it is not possible to describe precisely what a function does, then perhaps the function itself should be changed. Different kinds of functions should be named in slightly different ways. A function that does not return a value (a void function) or returns only function success information—in other words, those that return no data—should generally be named using an object verb name, such as CreateForm(), DisplayBitmap(), and OpenCommPort(). A member function of this type often does not require a qualifying object, because the object that calls the function generally can fulfill that role. If a function does return a data value, then the function should be named to reflect the nature of the return value, such as GetAverage(), log10(), and ReadIntervalTimeOut(). Some prefer to make the first word in a function name lowercase. This is a matter of personal preference, but consistency should be maintained.
Adhering to Naming Conventions How variables, types, and functions are named is an extensive topic, encompassing a myriad of concerns. Mentioning every convention that could be used is impossible. That being the case, you should endeavor to adhere to the following guidelines: • Name a variable or a function such that its purpose is obvious. If this means more typing, then so be it. • Name a type so that its intended use is obvious. Try not to use a name that is an obvious choice for a variable of the type. Prefixing a letter symbol can help. • Be consistent! With practice, even the most obscure naming system can be understood if it is consistently applied.
The Use of Code Constructs One of the best ways to improve the readability of code is through the appropriate use of code constructs—using the right tool at the right time for the right job. Therefore it is important to understand when to use const (and when not to), when to use references instead of pointers, which loop statement is most appropriate, whether to use multiple if-else statements or a single switch statement, when to represent something with a class and when not to, when to throw an exception and when to catch it, how to write an exception specification, and so on.
3 PROGRAMMING IN C++BUILDER
In general, function names can be longer than variable names, and if you need to write a long function name, you should not be overly concerned. However, take care to ensure that a long function name is not the product of a poorly designed function that tries to perform too many poorly related operations. In fact, you should endeavor to write functions that perform a single well-defined task, and the name of the function should reflect that. If you must write a function that does more than one thing, the name