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...

Sample applications

The chapters in this part show several complete examples of building applications with Delphi. Although each of the sample applications is a complete and useful application, the primary purpose of these chapters is to explain how to perform typical application-building tasks in Delphi within a realistic context. For example, the text editor example describes how to manipulate menu items, and the graphics example shows how to create and use tool bars. You will most likely use these techniques in...

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 objects to a string list

In addition to its list of strings, stored in the Strings property, a string list can also have a list of objects, which it stores in its Objects property. Like Strings, Objects is an indexed property, but instead of an indexed list of strings, it is an indexed list of objects. If you're just using the strings in the list, it doesn't matter whether you have objects the list does nothing with the objects unless you specifically access them. Also, it doesn't matter what kind of object you assign...

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...

Creating an ownerdraw control

Windows list-box and combo-box controls have a style available called owner draw, which means that instead of using Windows' standard method of drawing text for each item in the control, the control's owner (generally, the form) draws each item at run time. The most common application for owner-draw controls is to provide graphics instead of, or in addition to, text for items. The Delphi tab-set control also has a similar owner-draw style. Owner-draw controls have one thing in common they all...

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...

Adding associated objects

To associate an object with an existing string, you assign the object to the Objects property at the same index. For example, if a string list named Fruits contains the string 'apple' and you want to associate a bitmap called AppleBitmap to it, you would use the following assignment with Fruits do Objects IndexOf('apple') AppleBitmap You can also add objects at the same time you add the strings by calling the string list's AddObject method instead of Add, which just adds a string. AddObject...

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...

Restarting the program

Sometimes while debugging, you will find it necessary to restart the program from the beginning. For example, you might need to restart the program if you step past the location of a bug, or if variables or data structures become corrupted with unwanted values. To end the current program run and reset the program, choose RunlProgram Reset (or press Ctrl+F2). Resetting a program closes all open program files, releases resources allocated by calls to the VCL, and clears all variable settings....

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...

Using the Component Expert

Figure 2.19 The Component Expert dialog box 2 In the Class Name edit box, enter the name of the new class you are creating. Remember that all Object Pascal classes are generally prefaced with a letter T (for type). For example, the name of a new button component type could be TMyButton. 3 Use the drop-down list of the Ancestor Class combo box to select a base class, or enter the name of a base class for your new component. Unless you override them in the component declaration, your new...

Adding a menu

Up to this point, all the features you added to the graphics application use either direct interaction with the mouse or manipulation of tool-bar controls to activate them. The next few steps, however, deal with printing, loading, saving, and Clipboard operations. Although you can invoke these operations from tool bar buttons, the standard, expected interface for them uses menu commands. Menu creation is not a major topic of this example, however. If you do not know how to use the Menu Designer...

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...

Enabling the Help button from a common dialog box

There are three steps to enabling a Help button from a common dialog box 1 Display the button in the dialog box. 2 Specify a Help context for the dialog box component. 3 Specify the application Help file. To display a Help button in a common dialog box, set the Options l ShowHelp property to True. The ShowHelp setting is a nested property under the Options property for most common dialog box components. For each dialog box component, the ShowHelp property is prefaced with initials particular to...

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...

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...

Runtime errors

If your program successfully compiles, but fails when you run it, you've encountered a run-time error. Your program contains valid statements, but the statements cause errors when they're executed. For example, your program might be trying to open a nonexistent file, or it might be trying to divide a number by zero. The operating system detects run-time errors and stops your program execution if such an error is encountered. Without a debugger, run-time errors can be difficult to locate because...

Manipulating text in a Memo component

Once the user can open a new text file, you want to provide some basic text manipulation operations, such as alignment, word wrapping, and cutting, copying, and pasting. This application uses event handlers for the EditForm menu items to provide these options. Depending on the current condition of the text, these menu items might change during run time for example, a check mark might appear next to a menu item to indicate whether an option is selected, or a menu item might appear dimmed when...

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....

Specifying forms to autocreate

The form you specify as the project main form is always created loaded in memory when the application runs. The main form is also the first form loaded unless you specify otherwise in code. As you create additional forms for the project, these are also auto-created at run time. This has the advantage of having all forms in the application available to display without writing any code to specifically create the form you still need to show or hide the form . However, there might be times when you...

Subdividing a panel

Often you want to divide a panel, particularly one used for a status bar, into multiple, independent areas. Although you can achieve a similar effect by carefully formatting the text in a single panel, it's more efficient to use individual panels instead. To create panels within another panel, 1 Place a new panel within the panel. 2 Set any 3-D effects you want for the new panel. 3 Set the Align property of the new panel to alLeft. 4 Move the right side of the new panel to adjust its width. 5...

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...

Modifying the values of variables

Once you've evaluated a variable or data structure item, you can modify its value. Modifying the value of data items during a debugging session enables you to test different bug hypotheses and see how a section of code behaves under different circumstances. To modify the value of a data item, 1 Open the Evaluate Modify dialog box, then enter the name of the variable or data item you want to modify in the Expression edit box. 2 Click Evaluate to evaluate the data item. 3 Type a value into the...

Pasting graphics from the Clipboard

If the Windows Clipboard contains a bitmapped graphic, you can paste it into any image object, including image controls and the surface of a form. To paste a graphic from the Clipboard, 1 Call the Clipboard's HasFormat method to see whether the Clipboard contains a graphic. HasFormat is a Boolean function. It returns True if the Clipboard contains an item of the type specified in the parameter. To test for graphics, you pass CF_BITMAP. 2 Assign the Clipboard to the destination. In this example,...

Using the Save dialog box

Once users have created a new file, or modified an existing one, your code must enable them to save their work. You'll do this by means of a handler for the FileiSave event. In the text editor application, the event handler for the FrameForm FileiSave menu command interacts with the Save As dialog box to save the file. If the file has never been saved, choosing FileiSave opens the Save As dialog box, prompting the user to enter a file name. If the file has been saved and therefore named , no...

Converting text files back to DFM format

After editing an ASCII form file, you can convert the text-based form back into its regular binary .DFM format. Once you understand the structure and content of a form file, it's even possible for you to create a form by writing its structure as a text file and converting that to binary format. However, it's normally far more efficient to create forms with the visual tools that Delphi provides. To convert an ASCII-based form file back into binary .DFM format, 1 Choose FilelOpen File. You need...

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...

Updating the status bar

Once you have a status bar in a form, you need to update the status bar information. You can set the caption text of a panel at any time to reflect the status of the application. To update a status bar panel, set the panel's Caption property to reflect the current status. Add this caption-changing code to any event handlers that affect the status a particular panel reflects. Since the graphics program has two panels, you can update the drawing's origin point in OriginPanel when the user presses...

Disabling a watch

If you prefer not to watch an expression that you've entered in the Watch List window, but you don't want to delete it because you might need to use it later, you can disable the watch. Disabling watches speeds up the response of the debugger because it won't have to monitor the watch as you step or run through your program. In the Watch List window, the Enable check box lies to the left of each watch listing. When you set a watch, the debugger enables the watch by checking this box. To disable...

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...

Unit source code PAS files

Units are the main building blocks of Delphi applications. Unit files are identified by a .PAS file extension. They contain the Object Pascal source code for the elements of the Delphi applications you build. For example, every form has its own unit source code file. Unit source code files may initially be created as part of a project, but this is not required. You can create and save a unit as a stand-alone file that any project can use. Once you add a unit to a project, Delphi registers the...

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...

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...

Deleting breakpoints

When you no longer need to examine the code at a breakpoint location, you can delete the breakpoint from the debugging session. You can delete breakpoints using either the Code Editor or the Breakpoint List window Use the following methods to delete breakpoints From the Code Editor, place the text cursor in the line containing the breakpoint and press F5 or choose Toggle Breakpoint from the Speed Menu . Click the stop-sign glyph in the Code Editor window to delete the associated breakpoint....

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...

Hardware exceptions

Hardware exceptions can occur in two kinds of situations either the processor detects a fault it can't handle, or the application intentionally generates an interrupt to break execution. Hardware exception-handling is not compiled into DLLs, only into standalone applications. The SysUtils unit defines a generic hardware exception called EProcessorException. The RTL never raises an EProcessorException, but it provides a base from which the specific hardware exceptions descend. Table 7.4 shows...

Customizing pens and brushes

A graphics program that lets you only draw black-and-white images isn't very interesting. In order to use more colors, you need to modify the pen and brush the canvas uses to do its drawing and painting. In this section, you'll add more tool bars to the application, one each for the pen and brush. Specifically, you'll see how to perform the following tasks Hiding and showing tool bars

Changing the pen style

To change the style of a pen, set the pen's Style property to the value corresponding to the effect you want psSolid, psDash, psDot, psDashDot, psDashDotDot, or psClear. For this example, you could add click-event handlers for each of the pen-style buttons on the pen's tool bar, but instead, let's see how you can share one event handler for all the pen-style buttons. Different controls can all use the same event handler to handle events, as long as the events are compatible, meaning their...

Invalid breakpoints

If a breakpoint is not placed on an executable line of code, the debugger considers it invalid. For example, a breakpoint set on a comment, a blank line, or declaration is invalid. If you set an invalid breakpoint, the debugger displays the Invalid Breakpoint error box when you attempt to run the program. To correct this situation, close the error box and delete the invalid breakpoint from the Breakpoint List window. You can then reset the breakpoint in the intended location. However, you can...

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...

Placing a statusbar panel

In general, status bars appear at the bottom of a form. Aligning the status-bar panel to the bottom of the form takes care of both placement and resizing for you. To add a status bar panel to a form, 1 Place a panel component on the form. 2 Set the panel's Align property to alBottom. Once you've added the status-bar panel, you can subdivide it into separate status panels. If you're not going to subdivide, you probably want to set the BevelInner and BorderWidth properties to create a 3-D effect,...

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...

Using the integrated debugger

No matter how careful you are when you write code, a newly completed program is likely to contain errors, or bugs, that prevent it from running as it was designed to. Debugging is the process of locating and fixing the errors in your programs. Delphi contains an integrated debugger, so you can debug programs without leaving Delphi integrated development environment. The following topics are discussed in this chapter Planning a debugging strategy Starting a debugging session Controlling program...

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...

Formassociated unit files

The type of unit source code file you will probably work with most is the form-associated unit. This is the type of unit created whenever you open a new form. As introduced in Chapter 1, Delphi generates the following code for Unit1 of a default blank project, and for every unit with an associated blank form that you add to the project. Of course, the default unit identifier will be incrementally updated Unit2, Unit3, and so on as you add new forms. SysUtils, WinTypes, WinProcs, Messages,...

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...

Creating the frame form menu

The menu items in the text editor frame form provide users with various ways to manipulate child windows in the running application. Create the File and Window menus for the text editor frame form, as shown in Table 10.3. For each menu item, specify a value for the Caption property, and accept the values Delphi then creates for the Name property. Note that specifying a hyphen for the caption below the Open1 menu item on the file menu creates a separator bar. In later sections you'll set...

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...

Step Over

The Step Over command, like Trace Into, enables you to execute program statements one at a time. However, if you issue the Step Over command when the execution point is located on a function call, the debugger runs that function at full speed instead of tracing into it , then positions the execution point on the statement that follows the function call. To issue the Step Over command, choose from one of the following methods Press F8 default key mapping . Click the Step Over SpeedButton. As you...

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...