Working with graphics files

Graphic images that exist only for the duration of one running of an application are of very limited value. Often, you either want to use the same picture every time, or you want to save a created picture for later use. Delphi's image control makes it easy to load pictures from a file and save them again. Once you add the ability to load and save files, this sample application becomes a much more powerful tool. The logic for loading and saving graphics files is the same as for any other files,...

Adding a field to a form object

When you add a component to a form, Delphi also adds a field that represents that component to the form object, and you can refer to the component by the name of its field. Component fields are explained in Chapter 6. You can also add your own fields to forms by editing the type declaration at the top of the form's unit. In this example, the form needs to track whether the user has pressed a mouse button. To do that, you can add a Boolean field and set its value when the user presses the mouse...

Understanding scope

The scope of a variable, constant, method, type, or other identifier defines where the identifier is active. The identifier is local in scope to the smallest block in which it is declared. When your application is executing code outside the block in which an identifier is declared, that identifier is no longer in scope. That means the identifier is no longer available to the executing code. Only when code execution reenters the same block as the identifier declaration can the code access the...

Generating debugging information

Before you can begin a debugging session, you need to compile your project with symbolic debug information. Symbolic debug information, contained in a symbol table, enables the debugger to make connections between your program's source code and the machine code that's generated by the compiler. This way you can view the actual source code of your program while running the program through the debugger. Although Delphi generates symbolic debug information by default, you can manually turn on...

Drawing rounded rectangles

To draw a rounded rectangle on a canvas, you call the canvas's RoundRect method. The first four parameters passed to RoundRect are a bounding rectangle, just as for Rectangle or Ellipse. RoundRect also takes two more parameters that indicate how to draw the rounded corners. The following method, for example, draws a rounded rectangle in a form's upper left quadrant, rounding the corners as sections of a circle with a diameter of 10 pixels procedure TForm1.FormPaint(Sender TObject) begin...

Setting the exception address

Raising an exception sets the ErrorAddr variable in the System unit to the address where the application raised the exception. You can refer to ErrorAddr in your exception handlers, for example, to notify the user of where the error occurred. You can also specify a value for ErrorAddr when you raise an exception. To specify an error address for an exception, add the reserved word at after the exception instance, followed by and address expression such as an identifier. For example, given the...

Using nested for loops

Writing a for loop within another for loop is very useful when you want to display data in a table or a grid. This example uses the string grid. The code displays simple column and row titles in the nonscrolling or fixed regions of the grid, and then displays the column and row coordinates for each cell. When you click the Show Coordinates button, this appears in the grid Figure 5.9 A form with string grid displaying column and row coordinates 1 Place a string grid control and a button control...

Creating the application menus

The frame form menu bar serves as the main application menu. If the child form contains a menu bar, any menu items on it merge into the frame form's menu when a child window has focus at run time. For example, Figure 10.2 shows the text editor menu as it appears when the application first runs, with no child windows open Figure 10.2 Text editor application menu with no child windows open The File and Window menu items exist in the frame form, because they control functions of the frame, rather...

Drawing rectangles and ellipses

To draw a rectangle or ellipse on a canvas, you call the canvas's Rectangle or Ellipse method, passing the coordinates of a bounding rectangle. The Rectangle method draws the bounding rectangle Ellipse draws an ellipse that touches all sides of the rectangle. The following method, for example, draws a rectangle filling a form's upper left quadrant, then draws an ellipse in the same area procedure TForm1.FormPaint(Sender TObject) begin Canvas.Rectangle(0, 0, ClientWidth div 2, ClientHeight div...

Enumerated types

An enumerated type declaration lists all the values the type can have. These are some examples of enumerated type declarations TDays (Monday, Tuesday, Wednesday, Thursday, Friday, Saturday, Sunday) TPrimaryColor (Red, Yellow, Blue) TDepartment (Finance, Personnel, Engineering, Marketing, MIS) TDog (Poodle, GoldenRetriever, Dachshund, NorwegianElkhound, Beagle) These are some variables of those enumerated types DayOfWeek TDays Hue TPrimaryColor Department TDepartment DogBreed TDog Each value...

Using the Form Templates of the Browse Gallery

As mentioned earlier, the easiest way to share and reuse forms within and among Delphi projects is to use the Form Templates of the Delphi Browse Gallery. The Browse Gallery for Form Tempaltes is enabled in a default Delphi installation, but you can choose to disable it. To enable or disable the Browse Gallery in the environment, The Environment Options dialog box appears. 2 On the Preferences page, check or uncheck the Use On New Form check box, as appropriate, in the Gallery group box. (For...

Replacing the picture

You can replace the picture in an image control at any time. If you assign a new graphic to a picture that already has a graphic, the new graphic replaces the existing one. To replace the picture in an image control, assign a new graphic to the image control's Picture object. Creating the new graphic is the same process you used to create the initial graphic (see page 349), but you should also provide a way for the user to choose a size other than the default size used for the initial graphic....

Creating form menus

Menus provide an easy way for your users to execute logically grouped commands. The Delphi Menu Designer enables you to easily add a menu either predesigned or custom tailored to your form. You simply add a menu component to the form, open the Menu Designer, and type menu items directly into the Menu Designer window. You can add or delete menu items, or drag and drop them to rearrange them during design time. You don't even need to run your program to see the results your design is immediately...

Directory and Conditional options

On the Directories Conditionals page, you can control the location of the project's compiled output and specify the location of resources needed to compile, link, and distribute the application. If you want the compiled project output to be stored in a directory other than the project directory, you can enter a path in the Output Directory edit box. The specified directory must exist or be accessible at compile time or Delphi generates an error message. The Search Path edit box specifies the...

Working with objects in files

Saving OLE objects in files and restoring OLE objects from files was discussed in the section OLE data in files in Chapter 14. This application will use the SaveDialog and OpenDialog components to work with OLE data in files. This section describes the following steps involved in working with OLE objects in files To save an OLE object in a file, use the SaveToFile method of the OLEContainer component. For this example, use a SaveDialog component to enable the user to specify a file name and...

Creating nested submenus

Many application menus contain drop-down lists that appear next to a menu item to provide additional, related commands. Such lists are indicated by an arrow to the right of the menu item. Delphi supports as many levels of such nested, or submenus as you want to build into your menu. Organizing your menu structure this way can save vertical screen space. However, for optimal design purposes you probably want to use no more than two or three menu levels in your interface design. (For pop-up...

Trace Into

The Trace Into command executes a single program statement at a time. If the execution point is located on a call to a function that was compiled with debugging information, choosing Trace Into causes the debugger to step into that function by placing the execution point on the function's first statement. However, if the execution point is located on a function call that doesn't contain debugging information (a library function, for example), then choosing Trace Into runs that function at full...

The structure of a unit

Regardless of whether a unit is associated with a form, the basic structure of a unit is the same. The parts of a unit are uses < list of units> optional uses < list of units> optional implementation of procedures and functions The unit header starts with the reserved word unit, followed by the unit's name (an identifier). The next item in a unit is the reserved word interface, which indicates the beginning of the interface part of the unit the part visible to other units or...

Adding VBX controls

You can add VBX controls to the Delphi component library, so long as they conform to Microsoft Visual Basic 1.0 specifications. To do so, you specify the .VBX file that contains the control you want to add. Delphi then automatically creates a wrapper unit (a .PAS file) for the control to make it into a recognizable object type, and adds it to the list of installed units. You can specify a name for the control and which palette page you'd like it to appear on. To add a VBX control to the...

Selecting text

Before you can send any text to the Clipboard, the text must be selected. The function of reading and displaying selected text is native to the Memo and Edit components. In other words, you don't need to write code so that the Memo component can display selected text it comes with this behavior. The Stdctrls unit in Delphi provides several methods to work with selected text. (Recall that Delphi automatically adds the Stdctrls unit to the uses clause of any unit whose form contains a component...

Dropping objects

Dragging OLE objects from an OLE server application and dropping them on the OLE container application is an easy way to link or embed an OLE object into the OLE example application. By dragging and dropping, the user isn't required to use the Insert Object or Paste Special dialog box to specify an OLE object. The user simply grabs the OLE object from the OLE server with the mouse, drags it over the OLE example application, and drops it by releasing the mouse button. Note The material presented...

Setting component properties

This section discusses different ways you can set component properties at design time, in the context of creating the About box. Table 2.9 lists the properties you will set for the About box. You can also change property values while an application is running. This is discussed in the section, Setting properties at run time on page 59. For more information about the properties for each component, search online Help for the keyword components, or see the topic Visual Component Library...

Responding to a mousedown action

Whenever the user presses a button on the mouse, an OnMouseDown event goes to the object the pointer is over. The object can then respond to the event. In this example, the user will press the mouse button with the pointer over the form itself, at which time the application starts drawing. So you need to define the form's response to OnMouseDown events. To respond to a mouse-down action, you attach an event handler to the OnMouseDown event. If you're not sure how to create an event handler, see...

Declaring an enumerated type

The graphics program needs a way to keep track of what kind of drawing tool you want it to use at any given time. You could assign numbers to each kind of tool, but then you would have to remember what each number stands for. You can do that more easily by assigning mnemonic constant names to each number, but your code won't be able to distinguish which numbers are in the proper range and of the right type. Fortunately, Object Pascal provides a means to handle both of these shortcomings. You...

Removing a component from the tab order

In some cases you might want to prevent users from being able to tab to a component on a form. For example, there's usually no need for users to access a Panel component, because they can't modify it. You might want, in such a case, to remove the component from the tab order altogether. When the user presses the Tab key in the running application, the focus will skip over this component and go to the next one in the tab order. This is true even if the component has a valid TabOrder value. To...

Linker page

This page enables you to specify how the link options are configured. The two options that relate to project management are Include TDW Debug Info and the Default check box. Checking the Include TDW Debug Info check box causes debugging information to be compiled into the project executable file. This enlarges the size of that file. See online Help for information about using this or other options on the Linker page. Checking the Default check box preserves the settings on this page as the...

Comparing DDE and OLE

DDE and OLE are both for sharing data between applications. When should you use DDE and when should you use OLE DDE is good for exchanging distinct text strings. If all you want to know is the bottom line of a profits spreadsheet, it makes sense to link the cell that contains the bottom line to a Delphi DDE client application. Then you could output the data in an edit box or label. DDE protects the data in the spreadsheet by not allowing the user to activate and edit the spreadsheet from your...

Object scope

An object's scope determines the availability and accessibility of the data fields, properties, and methods within that object. Using the earlier bicycle analogy, if you were to add a headlight only to your customized bicycle object, the headlight would belong to that bicycle and to no other. If, however, the basic model bicycle object included a headlight, then all bicycle objects would inherit the presence of a headlight. The headlight could lie either within the scope of the ancestor bicycle...

Managing project content

Delphi's object-oriented architecture enables projects to use resources from a wide variety of physical locations. Some of the units in a project might reside in the project directory, while others might reside in the directory of the project that created them, or in some other directory. If you never reuse in other projects anything you create in one project, you'll have little difficulty keeping track of what files are being used in a project and where they reside. (You'll also miss out on...

Viewing forms and units

You can easily toggle between viewing the currently displayed form and its unit source code by using commands from the View menu, a keyboard shortcut, or the Project Manager. You can also view or edit any open unit or form by choosing commands from the View menu, buttons on the Project Manager SpeedBar, or commands from the Project Manager SpeedMenu. Toggling between form image and unit source code To switch between viewing the current form and its unit source code, use any of the following...

Project directories

Normally, you should store each Delphi project you create in its own directory. If you begin a project using any Project Template other than the Blank Project template, Delphi prompts you for a directory path and then (if necessary) creates the specified directory for the project. If you begin with the Blank Project template, Delphi saves it by default in the BIN directory, unless you specify otherwise. To avoid cluttering this directory, and potentially overwriting files, create the project...

Specifying the default new project

The default new project opens whenever you choose New Project from the File menu on the Delphi menu bar. In a new Delphi installation the Blank Project template is the default. You can specify any other Project Template (including a project you have created and saved as a Project Template) as the default new project. Alternatively, you can designate a Project Expert to run by default when a new project is begun. To specify a Project Template as the default new project, 1 Choose OptionslGallery...

Setting environment preferences

Delphi provides developers with a wide array of options for configuring the integrated development environment (IDE). References to the behavior and appearance of the IDE in this book are based upon the default configuration created by the Delphi installation program. If you are not working with a default installation of Delphi, bear in mind that another user might have modified parts of the IDE configuration. The Environment Options dialog box provides several pages of configuration options...

Using the Project Manager

The Delphi Project Manager provides a high-level view of the form and unit files listed in the uses clause of your .DPR file. (It looks at the in directive to get the file names.) You can use the Project Manager to open, add, save, and remove project files, and to open the Project Options dialog box, where you can configure project default settings. You access the Project Manager window by means of the View menu. If you share files among different projects, using the Project Manager is...

Opening the Menu Designer

To start using the Delphi Menu Designer, first add either a MainMenu or PopupMenu component to your form. Both menu components are located on the Standard page of the Component palette. Figure 3.12 MainMenu and PopupMenu components A MainMenu component creates a menu that's attached to the form's title bar. A PopupMenu component creates a menu that appears when the user right-clicks in the form. Pop-up menus do not have a menu bar. To open the Menu Designer, select a menu component on the form,...

Adding an image control

An image control is a kind of placeholder component. It allows you to specify an area on a form that will contain a picture object, such as a bitmap or a metafile. You can either set the size of the image manually or allow the image control to adjust to the size of its picture at run time. You can use an image control to hold a bitmap that isn't necessarily displayed all the time, or which an application needs to use to generate other pictures. The example in Chapter 13 uses image controls to...

Creating a backup of an entire project

Backing up a project can be a simple matter of copying directories or can involve some additional steps. This depends upon how your project directories are structured and whether the project uses files from outside its own directory tree. The project directory isn't encoded into the project (.DPR) file. The project file does, however, record the location of all constituent project files. If these files reside in subdirectories of the main project directory, than all path information is...

Public and private declarations

When you build an application using the Delphi environment, you are adding data fields and methods to a descendant of TForm. You can also add fields and methods to an object without putting components on a form or filling in event handlers, but by modifying the object type declaration directly. You can add new data fields and methods to either the public or private part of an object. Public and private are standard directives in the Object Pascal language. Treat them as if they were reserved...

Beginning new projects

As discussed in Chapter 1, you can choose from a number of options that control what occurs when you begin a new project in Delphi. In a default installation of Delphi, opening a new project displays a blank form, based on the Blank Project template. You can change this default behavior in several ways. By changing Gallery options, (setting Gallery options is discussed on page 124) you can Specify the default new project to be one of the other Delphi Project Templates, including any project you...

The Project Manager window

The Project Manager window displays information about the status and file content of the currently open project. It also provides quick access to project management functions, easy navigation among the constituent files, and access to project options through the SpeedBar and SpeedMenu. SpeedBar (contains six SpeedButtons) SpeedBar (contains six SpeedButtons) As shown in the preceding figure, the main elements of the Project Manager window are The Project Manager also has a SpeedMenu which you...

Adding templates to the Gallery

You can save your own projects and forms as templates and add them to those already available in the Gallery. This is helpful in situations where you want to enforce a standard framework for programming projects throughout an organization. For example, suppose you develop custom billing applications. You might have a generic billing application project that contains the forms and functionality common to all billing systems. Your business centers around adding and modifying features in this...

Changing a files attributes

Every file has various attributes stored by the operating system as bitmapped flags. File attributes include such items as whether a file is read-only or a hidden file. Changing a file's attributes requires three steps 2 Changing individual file attributes You can use the reading and setting operations independently, if you only want to determine a file's attributes, or if you want to set an attribute regardless of previous settings. To change attributes based on their previous settings,...

Specifying the default new form

The default new form opens whenever you choose FilelNew Form or use the Project Manager to add a new form to an open project. In a new Delphi installation, the Blank Form template is the default. You can specify any other Form Template, including a form you have created and saved as a Form Template, as the default new form. Or you can designate a Form Expert to run by default when a new form is added to a project. To specify the default new form for new projects, 1 Choose OptionslGallery to...

Manipulating components in your forms

This section demonstrates fundamental skills you need as you work with the components in your forms. If you're comfortable using controls in a graphical user interface (GUI) environment, much of the material discussed here such as selecting, sizing, and deleting components and so on might be familiar to you. You might not be familiar, however, with how to perform some of these common operations within the Delphi environment. This section shows you how to do so. In the context of designing a...

Overview of Delphi projects

When you create a Delphi application, you can start with a blank project, an existing project, or one of Delphi's application or form templates. A project consists of all the files needed to create your target application. This section introduces you to the core files in a Delphi project. It discusses the following topics Source code for units without forms When you first start Delphi, a blank project named Projectl opens. Figure 1.5 A default Delphi project Unit source code page tab (Code...

Elements of the Delphi interface

The elements of the Delphi programming environment were designed to provide you with the tools you need to quickly and intuitively develop high-performance applications. This section briefly describes each element. For more information, choose Programming Environment from the contents screen of online Help. Elements visible upon starting Delphi While many elements are visible as soon as you start Delphi, some others are not visible until needed, or until you activate them through menu commands...

Saving a project

This section explains how to save an open project to the directory created to store it (that is, the project directory). Note If the project was begun from a Project Template, the Gallery selection process creates the project directory. Otherwise, Delphi saves projects by default to the BIN directory, unless you specify otherwise. To save all open project files to the project directory, use one of the following methods Choose the Save Project button on the Delphi SpeedBar. Choose the Save...

Saving a separate version of the project file

Delphi enables you to save a separate version of an open project in a directory other than the project directory. The FilelSave Project As command initiates the process. However, because the open project might use shared files in addition to files that were created as part of the current project, the Save Project As command saves only a copy of the project source code (.DPR) file, project options settings (.OPT file), and the project resource (.RES) file to the new location. Important No unit...

Beginning a project with a Project Template

Delphi's Project Templates provide you with predesigned projects that you can use as a starting point for your applications. Project Templates are part of the Gallery (located in the DELPHI GALLERY directory), which also provides Form Templates and Experts. When you begin a project from a Project Template (other than the Blank Project Template), you are prompted to specify a project directory, a unique subdirectory in which to store the new project files. If you specify a directory that doesn't...

Iterating the strings in a list

Many times you need to perform an operation on each string in a list, such as searching for a particular substring or changing the case of each string. To iterate through each string in a list, you use a for loop with an Integer-type index. The loop should run from zero up to one less than the number of strings in the list Count - 1 . Inside the loop you can access each string and perform the operation you want. For example, here's a loop that iterates the strings in a list box and converts...

Adding a scrollable region

The are many times when an application needs to display more information than will fit in a particular area. Some controls, such as list boxes and memos can automatically scroll their contents. But other controls, and sometimes even forms full of controls, need to be able to scroll. Delphi handles these scrolling regions with a control called a scroll box. A scroll box is much like a panel or a group box, in that it can contain other controls, but a scroll box is normally invisible. However, if...

Unit files for procedures and functions

You can write custom procedures or functions within any source code unit, including those associated with a form file. You might, however, want to reuse the routines that you write. In this case, it's usually better to create a unit specifically to contain those routines. By creating stand-alone units that have no associated form, you can make your specialized procedures and functions easily available to other projects. To create a unit file not associated with a form, choose File INew Unit. It...

File manager example

This chapter presents all the steps necessary to create a small file manager application. Each section in the chapter builds on the previous sections, but the individual sections also explain discrete tasks. The material assumes you already know how to perform most of the basic Delphi tasks, such as placing components on a form and creating a menu. Those tasks are described in Chapter 2 and Chapter 3. The complete application appears under the DEMOS DOC directory and is called FILMANEX.DPR....

Modifying breakpoint properties

To view and modify the properties of a breakpoint, double-click the breakpoint in the Breakpoint List window or select it and choose Edit Breakpoint from the SpeedMenu. The Edit Breakpoint dialog box appears. Figure 8.2 The Edit Breakpoint dialog box In addition to examining a breakpoint's properties, you can use the Edit Breakpoint dialog box to change the location of a breakpoint, set a conditional breakpoint, and set a pass count for the breakpoint.

Multidimensional arrays

The arrays discussed so far are one-dimensional lists. Arrays can have many dimensions. Two-dimensional arrays can be used to hold all the values in a table, for example. This is how you would create a two-dimensional array that can hold all the values in a table that contains 20 columns and 20 rows TTable array 1 20, 1 20 of Double Then you can declare a variable of the TTable type var To initialize all the values in the table to 0.0, you could use nested for loops var for Col 1 to 20 do for...

Opening an existing text file

Your application can already present a new window where the user can enter and manipulate text. Now you can continue by providing the ability to open existing files in a child window. In the text editor application, you'll write event handlers for both the FrameForm Filel Open click and the EditForm FilelOpen click. As mentioned earlier, the event handler for the EditForm FilelNew click simply pointed to the event handler for the FrameForm File lNew click. In a similar way, the EditForm...

The project source code DPR file

The .DPR file is the main program file Delphi uses to compile all other units. Delphi updates this file throughout the development of the project. When you initially save the project, you are prompted to name the project source code file after being prompted to name any unit source code files the project contains . Since the project file is stored by the operating system, the file name must conform to DOS file naming rules. As introduced in Chapter 1, Delphi generates the following source code...

Unit object code DCU files

When you compile a project, Delphi creates an object code file for each unit. The file name is the same as the corresponding unit source file .PAS , and Delphi adds a .DCU extension. Thus, the object code file for UNIT1.PAS is UNIT1.DCU. The .DCU file is a binary file maintained by the Object Pascal compiler, so you should never need to open or modify this file by any other means. Note .DCU files are used to help achieve the high speed and efficiency of the Delphi compilation process. You do...

Using brushes

The Brush property of a canvas controls the way you fill areas, including the interior of shapes. Filling an area with a brush is a way of changing a large number of adjacent pixels in a specified way. The brush has three properties you can manipulate Color, Style, and Bitmap. The values of these properties determine the way the canvas fills shapes or other areas. By default, every brush starts out white, with a solid style and no pattern bitmap. You can set the color of a brush as you would...

Delphi components

The pages of the Component palette display the components Delphi provides to enable you to quickly develop powerful and diverse applications. A large part of interface design consists of using these components to customize the forms that make up your application. Delphi components include both visual and nonvisual types. Visual components appear essentially the same in your form at design time as they do at run time. Nonvisual components, on the other hand, are not visible on the form at run...

Formatting watch expressions

You can format the display of a watch expression using the Watch Properties dialog box. By default, the debugger displays integer values in decimal form. However, by checking the Hex Integer button in the Watch Properties dialog box, you can specify that an integer watch be displayed as hexadecimal. Figure 8.4 The Watch Properties dialog box Figure 8.4 The Watch Properties dialog box If you're setting up a watch on an element in a data structure such as an array , you can display the values of...

Set types

A set is a collection of elements of one type. That one type must be either an integer, Boolean, Char, enumerated, or subrange type. Sets are useful for checking if a value belongs to a particular set. Here is a simple application that uses a new set type. This is the finished form Figure 5.24 A form for a set type example 1 Place an edit box and a button on a form. Add a label above the edit box, and put a second label beneath the edit box. 2 Using the Object Inspector, change these properties...

Using a global variable

Suppose you wanted to keep track of the number of calculations performed while your application was running. You could modify your form to look like this Figure 5.15 A form that uses a global variable Figure 5.15 A form that uses a global variable 1 Add a fourth edit box to the form and a label to the left of the new edit box. 2 With the Object Inspector, make these changes Change the value of the edit box Name property to Counter. Change the caption of the new label to Number of Calculations....

Nesting if statements

You can put if statements within if statements when the logic of your application requires it. For example, the OKClick handler shown here can now test three conditions procedure TForm1.OKClick Sender TObject begin Label2.Caption 'Why are you working today ' else Label2.Caption 'You should be resting' else Label2.Caption 'Welcome to a new work week ' else As soon as a condition is met, the statement part runs and no further testing of conditions occurs. In other words, if you type Saturday in...

Assigning values to object variables

You can assign one object variable to another object variable if the variables are of the same type or assignment compatible, just as you can assign variables of any type other than objects to variables of the same type or assignment-compatible types. For example, if objects TForml and TForm2 are derived from type TForm, and the variables Forml and Form2 have been declared, you could assign Forml to Form2 You can also assign an object variable to another object variable if the type of the...

Adding a template form to a project

You can easily add any Form Template from the Delphi Browse Gallery to your application. You can also save any form you've designed as a template that gets installed into the Gallery. For more information about saving forms as templates, see Saving a form as a template on page 93. To add a template form to your project, 1 With a project open, choose FilelNew Form. The Browse Gallery dialog box appears, with the Blank Form option highlighted by default. If another form has been specified as the...

Deleting event handlers

When you delete a component, Delphi removes its reference in the form's type declaration. However, deleting a component does not delete any associated methods from the unit file, because as noted earlier, those methods might be called by other components in the form. You can still run your application so long as the method declaration and the method itself both remain in the unit file. If you delete the method without deleting its declaration, Delphi generates an Undefined forward error...

Using the drawing tools

Now that the application has the ability to specify different drawing tools, you need to make the event handlers apply the tool the user selects, which you've stored in DrawingTool. Your code now needs to choose how to draw, based on the selected tool. Drawing the appropriate shapes If you had only a few choices, you'd probably just rewrite the drawing methods to look something like this procedure TForm1.FormMouseUp Sender TObject begin if DrawingTool dtLine then draw a line else if DrawingTool...

Loading and saving string lists

You can easily store any Delphi string list in a text file and load it back again or load it into a different list . String list objects have methods to handle both operations. Using these methods, you can quickly create a simple text editor by loading a file into a memo component as shown in Chapter 10 . But you can also use the same mechanism to save lists of items for list boxes or complete outlines. To load a string list from a file, call the LoadFromFile method and pass the name of the...

Saving form files as ASCII text

Delphi enables you to save .DFM form files as ASCII text. You can then modify a form by using any standard text editor to edit the text file. Later, you can load the ASCII file in the Code Editor and convert it back into the binary .DFM format. This can be useful when using Delphi projects in a team development environment, or whenever version control is an issue, since most version control mechanisms depend on a text-based comparison. To convert a form file to ASCII format, 1 Choose FilelOpen...

Creating standardcommand buttons

You can quickly create buttons for many standard commands by adding BitBtn components to the form and setting the Kind property for each button. The possible Kind property settings and their effect are shown in the following table. In addition to the property settings shown, the bitmap button displays graphics, such as a green check mark for the OK button, or a red X for the Cancel button. Table 3.3 Delphi's predefined bitmap button types Appearance Equivalent property setting s Comments Makes...

Saving a form as a template

Once you've designed a custom dialog box, you might want to reuse it in other projects. One convenient way to do this is to save it as a Form Template. Saving a form as a template is similar to saving a copy of the form under a different name. When you save a form as a template, however, it then appears on the list of templates displayed in the Browse Gallery. You specify the bitmap and description of the template that appears in this template list. To save your current form as a template, 1...

Setting the focus in a dialog box

Only one component per form can be active, or have the focus, in a running application at any given time. The component having the focus by default corresponds to the ActiveControl property of the form, which can be set at design time, or used during run time to access the component that has focus. To change focus at run time, use the SetFocus method. When you design a dialog box, you usually want to specify which component should have focus when the dialog box first opens. For example, in a...

Tracking movement

The problem with the OnMouseMove event handler as currently written is that while it draws a line to the current position of the mouse, it draws that line from the last mouse position, not from the original position. Now that the application tracks the origin, however, that's easy to correct. Move the drawing position to the origin point, then draw to the current point procedure TForm1.FormMouseMove Sender TObject,-Button TMouseButton Shift TShiftState X, Y Integer Canvas.MoveTo Origin.X,...

Passing parameters

When your code calls a procedure or function, it often uses parameters to pass data to the called procedure or function. The section Calling procedures with parameters on page 160, describes how to use a parameter in calling a procedure the section Writing a procedure or function header on page 185, describes how to create a parameter list in a procedure or function header. This section describes the most common kinds of parameters your procedures and functions can use The Alpha variable...

Drawing straight lines

To draw a straight line on a canvas, use the LineTo method of the canvas. LineTo draws a line from the current pen position to the point you specify and makes the endpoint of the line the current position. The canvas draws the line using its pen. For example, the following method draws crossed diagonal lines across a form whenever the form is painted procedure TForm1.FormPaint Sender TObject begin with Canvas do begin LineTo ClientWidth, ClientHeight MoveTo 0, ClientHeight LineTo ClientWidth,...

Unit files for components

If you elect to write a new Delphi component, you need to create a unit file for the source code. The default structure of the unit source code for a new component differs somewhat from other unit files. You begin creating a new component unit file when you choose New Component from the File menu. For information on creating a component unit file, see Using the Component Expert in Chapter 2. You can find an example of unit file source code for a new component on page 72. The Delphi Component...

MDI and SDI forms

Any form you design can be implemented in your application as a Multiple Document Interface MDI or Single Document Interface SDI form. In an MDI application, more than one document or child window can be opened within a single parent window. This is common in applications such as spreadsheets or word processors. An SDI application, by contrast, normally contains a single document view. It's probably more common to design an MDI form as such from the beginning, but you can change forms you...

Directing your text file to the printer

The next few sections describe the parts of code that make up the FileiPrint OnClick event handler. You'll see how to write the complete event handler in Printing the contents of the memo on page 308. Before you begin printing, you need to assign a text-file variable to the printer by calling the AssignPrn procedure. The FileiPrint OnClick event handler, Print1Click, declares a local variable, PrintText, for a file of type Text, as defined by the System unit. Print1Click then passes this...

Adding scroll bars dynamically

Recall that you set the initial value of the ScrollBars property for the Memo component at design time. When the application first runs, the memo contains both vertical and horizontal scroll bars, and word wrap is not selected. If the user selects word wrap, then only the vertical scroll bar remains, as there is no need to scroll to the right because text wraps within the current size of the Memo component. The OnClick event handler for the CharacterlWordWrap command sets the value of the Memo...

Accessing a particular string

The string list has an indexed property called Strings, which you can treat like an array of strings for most purposes. For example, the first string in the list is Strings 0 . However, since the Strings property is the most common part of a string list to access, Strings is the default property of the list, meaning that you can omit the Strings identifier and just treat the string list itself as an indexed array of strings. To access a particular string in a string list, you refer to it by its...

Customizing project options

While the preceding section discusses how to create new projects using the default values of a new Delphi installation, your ability to control project options doesn't end there. Delphi offers you the option of customizing the integrated development environment IDE itself. The appearance and behavior of the IDE when you start Delphi or begin a new project are governed by the settings of several types of options Environment settings affect all Delphi projects. Gallery settings determine the...

Graphical form DFM files

As discussed in previous chapters, a file with a .DFM extension is a binary file that contains information about the graphical properties of a form. The visual display of a form at design time and at run time derives its information from this file. Delphi maintains a corresponding .DFM file for each form-associated unit source code file. If you develop forms exclusively with the visual tools provided by Delphi, you seldom, if ever, need to deal directly with .DFM files. Delphi updates them as...

Disabling and enabling breakpoints

Disabling a breakpoint hides the breakpoint from the current program run. When you disable a breakpoint, all the breakpoint settings remain defined, but the breakpoint is hidden from the execution of your program your program will not stop on a disabled breakpoint. Disabling a breakpoint is useful if you have defined a conditional breakpoint that you don't need to use now, but might need to use at a later time. 1 Open the Breakpoint List window and highlight the breakpoint you want to disable....

Printing the text file

The Delphi Printers unit contains routines that provide your application with all the printing capabilities users expect. The printing functionality written into the text editor represents only a subset of what you can provide in your Delphi applications. In the text editor application, you'll enable users to print the contents of the text file, or to print selected text. When printing a selection, the first line of selected text will be printed left-aligned, even if, for example, the selected...

Responding to a mouseup action

An OnMouseUp event occurs whenever the user releases a mouse button. The event usually goes to the object the mouse cursor is over when the user presses the button, which is not necessarily the same object the cursor is over when the button is released. This enables you, for example, to draw a line as if it extended beyond the border of the form. To respond to mouse-up actions, you define a handler for the OnMouseUp event. If you're not sure how to create an event handler, see Chapter 2. In...

Pasting objects

Some OLE server applications allow the user to copy or cut OLE objects to the Clipboard. If an OLE object is stored on the Clipboard, you can initialize an OLEContainer by allowing the user to use the Paste Special dialog box to paste the object into the OLE container application. This section describes the following steps involved in pasting OLE objects at run time Using the Paste Special dialog box Using OLE objects with the Clipboard To paste an OLE object into an OLEContainer component, use...

Constant parameters

If a formal parameter never changes its value when a procedure or function runs, you should consider using a constant parameter instead of a value parameter. Make a formal parameter a constant parameter by typing the reserved word const before the name of the parameter in the parameter list. Like a value parameter, a constant parameter can be any expression. Using a constant parameter instead of a value parameter, however, protects you from accidentally assigning a new value to the parameter...

Evaluating expressions

Choose Run Evaluate Modify to open the Evaluate Modify dialog box. Figure 8.5 The Evaluate Modify dialog box Figure 8.5 The Evaluate Modify dialog box By default, the word at the cursor position in the current Code Editor is placed in the Expression edit box. You can accept this expression, enter another one, or choose an expression from the history list of expressions you've previously evaluated. To evaluate the expression, click the Evaluate button at the bottom of the Evaluate Modify dialog...

Setting form properties for a dialog box

By default, Delphi forms have Maximize and Minimize buttons, a resizable border, and a Control menu that provides additional commands to resize the form. While these features are useful at run time for modeless forms, modal dialog boxes seldom need them. Delphi provides a BorderStyle property for the form that includes several useful values. Setting the form's BorderStyle to bsDialog implements the most common settings for a modal dialog box, such as Removing the Minimize and Maximize buttons...

Giving a variable a type

When declaring a variable, you must state its type. The type of a variable defines the set of values the variable can have. In general, you declare a variable where you want to use it. For example, if you want to use a variable in an event handler, you declare the variable within the event handler. For more details about where to declare variables, read the sections Object Pascal blocks on page 174 and Understanding scope on page 177. Precede all variable declarations with the reserved word...

Default check box

The Project Options dialog box displays a check box control labeled Default. This control enables you to modify some of Delphi's default project configuration properties. Checking this control writes the current settings from the Compiler, Linker, and Directories Conditionals pages of the Project Options dialog to a file called DEFPROJ.OPT. Delphi creates this file when you check the Default box and choose OK in the Project Options dialog box. Delphi then uses the project options settings...

Checking source code syntax

The Compile menu on the Delphi menu bar provides you the option of running a syntax check on your project's source code. The checking is identical to that for a compilation, and errors in your code generate the same error messages. However, the process is faster because Delphi makes no attempt to generate object code, and if the check succeeds, no executable file is generated. To run a syntax check on your project source code, 1 Save the project source code recommended but not required . 2...

Responding to the mouse

There are four kinds of mouse actions you can respond to in your applications. Three of these are uniquely mouse actions mouse-button down, mouse moved, and mouse-button up. The fourth kind of action, a click a complete press-and-release, all in one place is a bit different, as it can also be generated by some kinds of keystrokes such as pressing Enter in a modal dialog box . In this example, you'll respond to the unique mouse actions. You'll also see how clicks work when responding to tool-bar...

Setting the tab order

Tab order is the order in which focus moves from component to component in a running application when the Tab key is pressed. To enable the Tab key to shift focus to a component on a form, the TabStop property of the component must be set to True. The tab order is initially set by Delphi, corresponding to the order in which you add components to the form. You can change this by changing the TabOrder property of each component, or by using the Edit Tab Order dialog box. To use the Edit Tab Order...

The Form Style property

The FormStyle property determines whether the form is a frame or child form or a non-MDI application form . You set the FormStyle property only at design time. To create an MDI frame form, select the main form and use the Object Inspector to set its FormStyle property to fsMDIForm. There can be only one MDI frame form per application. Caution You can set any form's FormStyle property to fsMDIForm, but your application will not be compiled correctly if you do so for a form that is not specified...

Operating on objects in a string list

For each of the operations you can perform on a string list with a string, you can perform the corresponding operation with a string and its associated object. For example, you can access a particular object by indexing into the Objects property, just as you would the Strings property. The biggest difference is that you cannot omit the name Objects, since Strings is the default property of the string list. The following table summarizes the properties and methods you use to perform...

Inserting objects

At this point, the OLE example application is ready to contain OLE objects. This section describes the following steps involved in inserting OLE objects at run time Using the Insert Object dialog box Initializing the OLE container To insert an OLE object into an OLEContainer component, use the Insert Object dialog box. Recall from Chapter 14 that specifying the ObjClass or ObjDoc property of an OLEContainer component at design time displays the Insert Object dialog box. At run time, the...

Making a dialog box modal or modeless

At design time, dialog boxes are simply customized forms. At run time they can be either modal or modeless. When a form runs modally, the user must explicitly close it before working in another running form. Most dialog boxes are modal. When a running form is modeless, it can remain onscreen while the user works in another form for example, the application main form . You might create a modeless form to display status information, such as the number of records searched during a query, or...

Value parameters

With the exception of the code example in the previous section, Forward declarations, value parameters are the only type of parameters discussed in this chapter so far. A formal value parameter is a copy of the actual value parameter. In other words, the compiler puts the actual parameter at one memory address, and the formal parameter at another memory address. Therefore, the called procedure or function can change the value of the formal parameter, yet the value of the actual parameter...