Home

Accessories for File Processing

 

Files

 

Introduction

A file is a series of bits of data that are arranged in a particular way to produce a usable document. For easy storage, location, and management, the bits are stored on a medium such as a hard disc, a floppy disc, a compact disc, or any valid and supported type of storage. When these bits belong to a single but common entity, the group is referred to as a file. For even greater management, files can be stored in a parent object called a directory or a folder. Since a file is a unit of storage and it stores information, it has a size which is the number of bits it contains. To manage it, a file also has a location also called a path that specifies where and/or how the file can be retrieved. Also, for better management, a file has attributes that indicate what can be done on a file or that provide specific information that the programmer or the operating system can use when dealing with the file.

File processing consists of creating, storing, and/or retrieving the contents of a file from a recognizable medium. For example, it is used to save word-processed files to a hard drive, to store a presentation on floppy disk, or to open a file from a CD-ROM. To perform file processing on VCL applications, you have four main choices, two derived from C and C++ languages, one or a few classes provided by the Visual Component Library, or use the Win32 API.

Characteristics of a File

In order to manage files stored in a computer, each file must be able to provide basic pieces of information about itself. This basic information is specified when the file is created but can change during the life time of a file.

To create a file, a user must first decide where it would be located: this is a requirement. A file can be located on the root drive. Alternatively, a file can be positioned inside of an existing folder. Based on security settings, a user may not be able to create a file just anywhere in the (file system of the) computer. Once the user has decided where the file would reside, there are various means of creating files that the users are trained to use. When creating a file, the user must give it a name following the rules of the operating system combined with those of the file system.

At the time of this writing, the rules for file names were on the MSDN web site at Windows Development\Windows Base Services\Files and I/O\SDK Documentation\Storage\Storage Overview\File Management\Creating, Deleting, and Maintaining Files\Naming a File (because it is a web site and not a book, its pages can change anytime).

The most fundamental piece of information a file must have is a name. Once the user has created a file, whether the file is empty or not, the operating system assigns basic pieces of information to it. Once a file is created, it can be opened, updated, modified, renamed, etc.

Introduction to Common File Dialog Boxes

Because files on a computer can be stored in various places, Microsoft Windows provides various means of creating, locating, and managing files through objects called Windows Common Dialog Boxes. Indeed, these dialog boxes are part of the operating system and are equipped with all the necessary operations pertinent to their functionality. To support this, Borland C++ Builder ships these ready-made dialog boxes so that, instead of, or before creating a new commonly used dialog box, first find out if C++ Builder already provides an object that can do the job. The objects of C++ Builder are highly efficient and were tested enough to be reliable. This means that whenever possible, you should use them.

To use a standard Windows dialog box, from the Dialogs tab of the Tool Palette, click the desired dialog’s button and click anywhere on the form. The position of the control on the form has no importance because it is only a representative. It will not appear when the form is running. Once the desired dialog’s icon is on the form, place a button that will be used to call the dialog. A dialog is called using the DialogName->Execute() method. You can find out what button the user clicked when closing the dialog, and act accordingly.

Practical Learning Practical Learning: Introducing Common Dialogs

  1. Start Borland C++ Builder and create a new VCL Forms Application
  2. Save it in a new folder named FileProcess1
  3. Save the unit as Exercise and save the project as FileProc
  4. Change the Caption to File Processing

The Save As Dialog Box

 

Overview of the Save As Dialog Box

Most of the applications users open display an empty document. In other words, users are supposed to create files. Once a file has been created, a user would usually want to store the contents of that file on a media (hard drive, floppy disk, etc). Microsoft Windows provides a common dialog box for this purpose: The Save As dialog box:

The primary role of the Save As dialog box is to allow users to store a file on the hard drive of the computer, on a portable media such as a floppy disk, or on a network drive. To make this efficient and complete, the user must supply two valuable pieces of information: the location and the name of the file. The location of a file is also known as its path.

The name of a file follows the directives of the operating system. On MS DOS and Windows 3.X, it had to be in an 8.3 format. The actual name had to have a maximum of 8 characters with restrictions on the characters that could be used. The user also had to specify three characters after a period. The three characters, known as the file extension, were used by the operating system to classify the file. That was all necessary for those 8-bit and 16-bit operating systems.

Various rules have changed. For example, the names of folders and files on Microsoft Windows >= 95 can have up to 255 characters. The extension of the file is mostly left to the judgment of the programmer but the files are still using extensions. Applications can also be configured to save different types of files; that is, files with different extensions.
To use the Save As dialog box, users usually click an item under the File menu. Here is how it works for most regular applications. The user creates a new file. If the user wants to save the file, she can click File -> Save. If the file was not previously saved, the application would call the Save As dialog box. If a file is displaying, whether it was saved previously or not, the user can also click File -> Save As... which also would call the Save As dialog box.

Two objects are particularly important on the Save As dialog box: The Save In combo box and the File Name edit box or combo box (the File Name box is made of a combo box to make it user-friendly but over all, users hardly use the list side of this combo box). Since Windows 95, the user does not have to specify an extension if the programmer makes it easy. To help with this, the Save As dialog box is equipped with a Save As Type combo box. This combo box allows the user to select one of the extensions. The available extensions have to be created by the programmer so the user can select from this preset list. If the programmer neglects this, the user would have no extension to select from. Although the file can still be saved, the operating system would not associate it with a known type of file. Therefore, if you specify a series of extensions, the user can select one of these and, in the File Name box, she can simply type a name for the file. If the user does not specify an extension, the operating system would allocate the extension of the Save As Type combo box. Users of regular commercial applications, such as word processors, spreadsheet programs, or databases, etc, are usually trained not to care about the extensions and let the application deal with that detail. In some other circumstances, the users must pay close attention to the extension they give a file (this is common on web development or graphics design).

After working on a Save As dialog box, the user can click Save or press Enter, which would validate her entries. To change her mind, regardless of what she did on the Save As dialog box, she can click Cancel or press Esc, which would dismiss the dialog box and ignore what she did (in reality, some actions cannot be ignored, such as creating a new file or folder inside of the Save As dialog box, deleting, cutting, or pasting files, etc; but if the user clicked Cancel or pressed Esc, the new file would not be saved).

Save As Dialog Box Creation

In the VCL, the Save As dialog box is performed using the TSaveDialog class. To visually add a file saving capability to your application, on the Dialogs property page of the Tool Palette, you can click the SaveDialog button SaveDialog and click on a form.

Alternatively, if you cannot add a SaveDialog control at design time, you can create one at run time when you need it in an event or a function. If you want the dialog box to be accessible to more than one event or function, you can declare a pointer to a TSaveDialog class. Here is an example:

private:
	AnsiString CurrentFile;
	TSaveDialog * dlgSave; // User declarations
public: // User declarations
	__fastcall TForm1(TComponent* Owner);
};

To make the control available to the form, you can initialize it in the constructor of the form as follows:

//---------------------------------------------------------------------------
__fastcall TForm1::TForm1(TComponent* Owner)
: TForm(Owner)
{
	dlgSave = new TSaveDialog(Form1);
}
//---------------------------------------------------------------------------

Eventually, when the form closes, you can make sure the memory occupied by the control is freed by deleting the dynamic control. This can be done in the OnDestroy event of the form:

//---------------------------------------------------------------------------
void __fastcall TForm1::FormDestroy(TObject *Sender)
{
	delete dlgSave;
	dlgSave = NULL;
}
//---------------------------------------------------------------------------

Characteristics of the Save As Dialog Box

To make sure that your application can open the allowed types of files for your application, depending on your goals, you should create a list of extensions that you want the users to be able to open. The allowed extensions form a group called a filter. The filter is like a funnel that selects the good items. For a text-based application, you may allow only text files, that is, files with a txt extension. For a rich text-based application, you may allow only Rich Text Format files, which are files with rtf extension. On the other hand, if you are creating an application for web files, you can allow as many file extensions as necessary, such as htm, html, php, asp, etc. As you may realize, text files or web files are all text-based files. This means that if you create a text-based or rich-text based application, you should allow the users to decide whether the file they are trying to open can be "read" by a text-based control. To provide this ability, you can specify an unknown extension specified as All Files.

To create a list of allowable extensions for your SaveDialog object, use the Filter property from the Object Inspector. At run time, you can create a list of file extensions as a string. If the Save dialog box will need only one extension, you can create the string using the following syntax:

Prompt|Extension

The Prompt is a section that defines what the user would see in the Save As Type combo box. An example would be 24-bit Bitmap. Such a string does not let the user know what actual extension the file would use. Therefore, as a courtesy, you can specify, between parentheses, the extension that would be applied if this extension is used. Therefore, the Prompt can be 24-bit Bitmap (*.bmp). In this case, the extension used would be bmp. The asterisk * lets the user know that whatever is provided as the file name would be used in place of the asterisk. The period indicates the separation from the file to its extension. This means that the characters on the left of the period would be the file name, the characters on the right side of the period would be used as the actual file extension.

To specify the extension that the operating system would use to associate to the file, you provide a second part of the string as Extension. In Microsoft Windows, most extensions are made of three characters. Some applications use a 2-letter extensions (for example Perl files have a pl extension) and some others use 4 letters (such as html for some HTML files). This depends on the programmer (or the company that is publishing the application). An example of a string the species an extension is:

24-bit Bitmap (*.bmp)|*.bmp

If you want to provide various extensions to your Save dialog box, you can separate them with a | symbol. An example would be:

HTML Files (*.htm)|*.htm|Active Server Pages (*.asp)|*.asp|Perl Script (*.pl)|*.pl

To make the extensions available to the SaveDialog control, you can assign the string to the Filter property. Here is an example:

//---------------------------------------------------------------------------
__fastcall TForm1::TForm1(TComponent* Owner)
: TForm(Owner)
{
	dlgSave = new TSaveDialog(Form1);
	dlgSave->Filter = "HTML Files (*.htm)|*.htm|"
			  "Active Server Pages (*.asp)|*.asp|"
			  "Apache Files (*.php)|*.php|"
			  "Perl Script (*.pl)|*.pl|"
			  "All Files";
}
//---------------------------------------------------------------------------

This would produce:

Once you know the types of files that your application will be dealing with, you can make your dialog box friendly by displaying the most likely extension for a document created using your application. For example, if you create a Memo-based application, users are more likely to create a text file with it. If you create a RichEdit-based application, users are more likely to create a Rich Text Format file with it. This most likely extension is known as the default extension, it allows the user not to specify an extension. By simply providing a file name and clicking Save, the operating system would associate the file with the default extension. Of course, if you create a filter, the user can specify a desired allowed extension.

To specify the default extension for your SaveDialog object, type the desired extension in the DefaultExt field of the Object Inspector.

If you had created a Filter and if you provide a default extension for a SaveDialog object, make sure it is one of the file extensions specified in the Filter list.

Microsoft Windows operating systems, especially since Windows 9X, are configured to have a default folder in which users are most likely to save their files. On Windows 9X, it is C:\My Documents. On Windows NT, it is usually specified by the network administrator. On Windows 2000 and Windows XP, it uses a more customized scenario. These settings are known to the operating system and you will usually not be concerned with them. In a rare circumstance, if you want to specify in which folder the users should save their files by default, you can provide it in the InitialDir property. This directory usually ends with \My Documents. If you want to find the path to the My Documents for a user, you can call the SHGetFolderPath(). Its syntax is:

HRESULT SHGetFolderPath(
	HWND hwndOwner,
	int nFolder,
	HANDLE hToken,
	DWORD dwFlags,
	LPTSTR pszPath
);

Here is an example:

//---------------------------------------------------------------------------
#include <vcl.h>
#include <shfolder.h>
#pragma hdrstop

#include "Unit1.h"
//---------------------------------------------------------------------------
#pragma package(smart_init)
#pragma resource "*.dfm"
TForm1 *Form1;
//---------------------------------------------------------------------------
__fastcall TForm1::TForm1(TComponent* Owner)
	: TForm(Owner)
{
}
//---------------------------------------------------------------------------
void __fastcall TForm1::Button1Click(TObject *Sender)
{
	char strBuffer[MAX_PATH];
	SHGetFolderPath(NULL,
			CSIDL_PERSONAL,
			NULL,
			NULL,
			strBuffer);

	Edit1->Text = strBuffer;
}
//---------------------------------------------------------------------------

Once again, most of the time, you will not be concerned with this issue if you are creating an application for any user.

Probably the most important issue users care about, as far as they are concerned, is a name for the file they are trying to save. Users know that they can set the name of the file in the File Name box. To make their saving a little faster, you can provide a default name for a file in case a user does not want to specify a file name. This is done by typing a name in the FileName field of the Object Inspector. In practicality, the FileName value is the string that displays in the File Name box of the Save As dialog box.

Practical Learning Practical Learning: Using the Save As Dialog Box

  1. On the Dialogs tab of the Tool Palette, click the SaveDialog button and click the form
  2. While the Save Dialog1 button is still selected on the dialog, in the Object Inspector, click the DefaultExt field and type rtf
  3. Click Filter and click its ellipsis button
  4. Complete the Filter Editor dialog box as follows:
     
  5. Click OK
  6. Click Title, type Save File As and press Enter
  7. Click an empty area on the form to select it
  8. In the Object Inspector, click the Events tab and double-click OnDblClick
  9. Implement the event as follows:
     
    //---------------------------------------------------------------------------
    void __fastcall TForm1::FormDblClick(TObject *Sender)
    {
    	if( SaveDialog1->Execute() == True )
    	{
    		ShowMessage("The Save button was clicked or Enter key was pressed"
    			    "\nThe file would have been saved as " +
    			    SaveDialog1->FileName);
    	}
    	else
    		ShowMessage("The Cancel button was clicked or Esc was pressed");
    }
    //---------------------------------------------------------------------------
  10. Execute the application. To test the Save As dialog box, double-click anywhere on the form
     
  11. Close the application and return to Borland C++ Builder

The Open File Dialog Box

 

Introduction

One of the most usual involvements with computer files consists of opening them for review or for any other reason the user judges appropriate. Microsoft Windows provides a convenient dialog box to handle the opening of files. The job is performed by using the Open File dialog box:

  

Open File Dialog Box Creation

To provide the means of opening files, you can use the TOpenDialog class. The easiest way to use it is to click the OpenDialog button from the Dialogs tab of the Tool Palette and click on the form. The OpenDialog icon can be positioned anywhere on the form because it would not be seen at run time. After placing it on the form, you can use the Object Inspector to configure it.

If you prefer to dynamically create an Open dialog box, declare a pointer to TOpenDialog and use the new operator to call its constructor and specify its owner. The technique is the same we applied for the TSaveDialog class. Here is an example:

TOpenDialog *OpenMe = new TOpenDialog(Form1);

Characteristics of an Open Dialog Box

One of the most important properties of an Open dialog box is the file it presents to the user. This is represented by the FileName property. If you want a default file to be specified when the dialog box comes up, you can specify this in the FileName property of the Object Inspector. If you need to use this property, you should make sure the file can be found. If the file is located in the same folder as the application, you can provide just its name. If the file is located somewhere in the hard drive, you should provide its complete path. Most of the time, you will not be concerned with this property if you are creating an application that will allow the user to open any file of her choice. Once a file is located, it can be accessed using the TOpenDialog::FileName property.

To make your application more effective, you should know what types of files your application can open. This is taken care by specifying a list of extensions for the application. To control the types of files that your application can open, specify their extensions using the Filter Property. The Filter string is created exactly like that of a SaveDialog control as we saw earlier.

Like the SaveDialog control, the default extension is the one the dialog box would first filter during file opening. If you want the Open File dialog to easily recognize a default type of file when the dialog box opens, you can specify the extension's type using the DefaultExt property.

For convenience, or for security reasons, Open File dialog boxes of applications are sometimes asked to first look for files in a specific location when the Open File dialog box comes up. This default folder is specified using the InitialDir property.

The essence of using the Open File dialog box is to be able to open a file. This job is handled by the Execute() method which is easily called using a pointer to the OpenDialog object you are using.

Practical Learning Practical Learning: Using the Open Dialog Box

  1. On the Dialogs tab of the Component, click the OpenDialog button and click the form
  2. While the OpenDialog1 icon is still selected on the form, in the Object Inspector, click DefaultExt and type rtf
  3. Click Filter and click its ellipsis button
  4. Complete the Filter Editor dialog box as follows:
     
  5. Click OK
  6. Click Title, type Open an Existing Document and press Enter
  7. Click an unoccupied area on the form to select it and, in the Object Inspector, click the Events property page
  8. Double-click the OnMouseDown field and implement the event as follows:
     
    //---------------------------------------------------------------------------
    void __fastcall TForm1::FormMouseDown(TObject *Sender, TMouseButton Button,
    				      TShiftState Shift, int X, int Y)
    {
        if( Button == mbRight )
        {
    	if( OpenDialog1->Execute() == True )
    	{
    		ShowMessage("The Open button was clicked or the Enter key was pressed"
    			    "\nThe " + OpenDialog1->FileName +
    			    " file would have been opened.");
    	}
    	else
    		ShowMessage("The Cancel button was clicked or Esc was pressed");
        }
    }
    //---------------------------------------------------------------------------
  9. Test the application:
     
  10. After using it, close it and return to Borland C++ Builder

The Browse For Folder Dialog Box

 

Introduction

The Visual Component Library ships with other dialog boxes useful for tasks that involve files, such as letting the user browse the hard drive to select a folder. This can be done using the Browse For Folder dialog box:

The VCL provides a convenient dialog box used to browse the drives of the user’s computer or a computer on the network to locate a folder or a mapped drive.

Creation of a Browse for Folder Dialog Box

The Browse For Folder dialog box is made available through the SelectDirectory() function. Its syntax is:

bool __fastcall SelectDirectory(const AnsiString Caption,
				const WideString Root,
				AnsiString &Directory);

This function takes three arguments and returns two values. The Caption parameter displays under the title bar but above the tree view of the dialog box. The Root value is a string that represents the name of the root drive. The Directory string is the default path folder. This function returns a Boolean value upon exiting. Here is an example of using the SelectDiretory() function:

//---------------------------------------------------------------------------
void __fastcall TForm1::btnDirectoryClick(TObject *Sender)
{
	AnsiString Caption = "Select a Directory";
	const WideString Root = "C:\"";
	AnsiString Directory = "C:\\Program Files";
	SelectDirectory(Caption, Root, Directory);
}
//---------------------------------------------------------------------------

When the dialog box opens, it displays two buttons: OK and Cancel. The OK button is disabled because no directory would have been selected. To use the Browse For Folder dialog box, the user clicks the + button to expand a folder, and the – (if any) button to collapse a folder. Once the user locates the desired folder, he must click it to highlight it, which enables the OK button.

After using the Browse For Folder dialog box, if the user clicks Cancel or presses Esc, whatever change was made would be dismissed and the function would return false. If the user clicks OK or presses Enter, the function would return the full path of the folder the user had selected. This path is the returned Directory argument. You can use a conditional statement to find out what button the user had clicked then use the returned Directory string as you see fit. Here is an example:

//---------------------------------------------------------------------------
void __fastcall TForm1::btnDirectoryClick(TObject *Sender)
{
	AnsiString Caption = "Select a Directory";
	const WideString Root = "C:\"";
	AnsiString Directory = "C:\\Program Files";

	if( SelectDirectory(Caption, Root, Directory) == True )
		edtInstallation->Text = Directory;
}
//---------------------------------------------------------------------------

The Select Directory Dialog Box

 

Introduction

An overloaded version of the SelectDirectory() function allows performing a different type of folder selection:

Creation of the Select Directory Dialog Box

To make available a Select Directory dialog box to your application, you can call the SelectDirectory() function using the following syntax:

bool __fastcall SelectDirectory(AnsiString &Directory,
				TSelectDirOpts Options,
				int HelpCtx);

Like the other SelectDirectory() function, this version returns two values: a Boolean type and a string. Once again, the Directory argument is required, although it is used as a sample that the user can change. Since the root drive is not a directory, you cannot set its value as “C:”, “C:\””, “A:”, “A:\”” or the likes. The Directory value must be a valid path of an existing folder. When the dialog displays, the string of the Directory is selected, which enables the OK and the Cancel buttons. Here is an example:

//---------------------------------------------------------------------------
void __fastcall TForm1::Button2Click(TObject *Sender)
{
	AnsiString Directory = "F:\\Corel\\WordPerfect Office 2002\\Graphics";
	SelectDirectory(Directory, TSelectDirOpts(), 0);
}
//---------------------------------------------------------------------------

On the computer used for this exercise, the function produced:

Notice the absence of a Directory Name edit box.

Once again, the user can change the displaying folder. This time, to proceed, the user would double-click a folder in the Directories tree view to expand the folder. Once the user has located the desired folder, he must click it to highlight it. After selecting a folder, the user would click OK. In this case the function would return true and the path of the folder. Two options not available on the first CreateDirectory() version can be used here. If you want to display the Directory Name edit box, set the TSelectDirOpts option set to at least:

TSelectDirOpts() << sdAllowCreate

If the user wants to use a directory that does not exist, if the directory can be created, add the sdPerformCreate option to the set as follows:

TSelectDirOpts() << sdAllowCreate << sdPerformCreate;

If the user types a directory that does not exist, it would be created transparently. If you want the user to confirm that he wants to create a new folder, add the sdPrompt option to the set. Here is an example:

//---------------------------------------------------------------------------
void __fastcall TForm1::Button2Click(TObject *Sender)
{
	AnsiString Directory = "C:\\Program Files\\Borland\\Delphi4\\Projects";
	SelectDirectory(Directory, TSelectDirOpts() << sdAllowCreate
			<< sdPerformCreate << sdPrompt, 0);
}
//---------------------------------------------------------------------------

The last option allows you to specify a help file to provide context sensitive help to the user. To use it, associate an integer that is mapped to the appropriate identifier in the Help file. Once you set this argument and the application has a help file, a Help button would appear on the dialog box. Here is an example of using the help argument:

//---------------------------------------------------------------------------
void __fastcall TForm1::Button2Click(TObject *Sender)
{
	AnsiString Directory = "C:\\Program Files\\Borland\\Delphi4\\Projects";
	const int HelpMe = 12;
	SelectDirectory(Directory, TSelectDirOpts() << sdAllowCreate
			<< sdPerformCreate << sdPrompt, HelpMe);
}
//---------------------------------------------------------------------------

The Print Dialog Box

 

Printing: An Overview

Another operation users perform on a file is to print it. Printing is the ability to render, on paper, the result of a control's contents. This is performed using an external device called a peripheral. To do this, users need access to a printer device. There are two main ways users print a document or file. They can ask the application they are using to send the document directly to a printer, or they can use a dialog box to decide how the printing should be done.

To directly send a document to the printer, you need to make sure that the control, whose value needs to be printed, supports printing. To accommodate the users of such an application, you can provide a menu item or a button they would click. An example of such a button would be . To print, the user can click this button. That is the case when using WordPad; its Standard toolbar is equipped with such a button. With this type of printing, when the user decides to print, the whole document would be printed "as is", in color if the document is colored and if the printer supports colors. If there are more than one printer, the computer would use what is known as the default printer.

If you want users to be able to configure or customize the printing process, Microsoft Windows provides a common dialog box called Print:

The print dialog box allows a user to select a printer if more than one are available. The user can decide either to print the whole document, to print a range of pages, or to print a portion of the document that was previously selected. The user can also decide on the number of copies to print from the document, the range specified, or the selected portion. Furthermore, the user can access the particular characteristics of the selected printer and specify how the printer should perform the job. For example, if the selected printer can print in color and the document is in color but the user wants to print in black and white, she can specify this using the Properties button.

The Process of Printing

There are various ways you can deal with printing (printing is actually one of the most difficult tasks to program). The first thing you should do is to let the users know that printing is available on your application. This is usually done by providing a menu item called Print or a button on a toolbar with a printer-like bitmap.

The easiest and fastest way to send a document to the printer, if the control that holds the document directly supports printing, is by calling the Print() method. For example, since the TRichEdit class and its associated control the RichEdit support printing, you can simply call the TRichEdit::Print() method. This method takes one argument as the name of the document that needs to be printed. The argument can be the name of the file. If you do not have a specific name, you can type anything or specify an empty string. Here is an example:

//---------------------------------------------------------------------------
void __fastcall TForm1::Button1Click(TObject *Sender)
{
	RichEdit1->Print("Mother and Father");
}
//---------------------------------------------------------------------------

If you want to allow your users to customize or control their printing, you can provide them with the Print dialog box:

In the VCL, the Print dialog box is represented through the TPrintDialog class. To add printing during the design of your application, on the Dialogs property sheet of the Tool Palette, you can click the PrintDialog button and click on the form.

If you want to programmatically provide a Print dialog box, you can declare a pointer to TPrintDialog class. The compiler will need to know "who" owns the printer. This can be done as follows:

// Adding a Print dialog box at run time
TPrintDialog *dlgPrint = new TPrintDialog(Form1);

Using a menu item or a toolbar button, you can call the Execute() method of the TPrintDialog class. As a Boolean function, you should first make sure that the user was able to open the Print dialog box, then you can execute printing. Suppose you have a RichEdit control whose content you want to print and suppose you have added a menu item called mnuPrint and a PrintDialog control named PrintDialog1, you can perform printing with the following code:

//---------------------------------------------------------------------------
void __fastcall TForm1::mnuPrintClick(TObject *Sender)
{
	if( PrintDialog1->Execute() )
		RichEdit1->Print("");
}
//---------------------------------------------------------------------------

The TPrintDialog class provides all the options to customize the behavior of the Print dialog box.

One of the first choices people make when printing is whether to print the whole document or just sections of it. By default, the Print dialog box always allows users to print the document completely. This is represented by the All radio button. Most other characteristics of the Print dialog box are not singly set. A particular characteristic usually works in connection with another effect of the same Print dialog box.

When customizing the Print dialog box, you will mostly set its options using the Options property with one or more other related properties. The Options property is a set; this means that it allows you to combine the options you want. If you want users to be able to select a portion of text and print only the selected portion, you must make sure the Selection radio button is available. This is done by setting the poSelection option to true. If you want the dialog box to appear with the Selection radio button selected, you can set the PrintRange property to prSelection. Usually this would not be a standard good idea. If you want this radio button to be selected when the dialog box comes up, you should first make sure that a portion of the document to be printed has been selected. For example, if you are (or the user is) trying to print from a RichEdit control, you can check whether there is already selected text before displaying the dialog box as follows:

//---------------------------------------------------------------------------
void __fastcall TForm1::btnPrinterClick(TObject *Sender)
{
	if( RichEdit1->SelLength )
		PrintDialog1->PrintRange = prSelection;
	else
		PrintDialog1->PrintRange = prAllPages;

	if( PrintDialog1->Execute() )
		RichEdit1->Print("");
}
//---------------------------------------------------------------------------

By default, the range of pages to print from the document is not available to the users. If you want the users to be able to set the range, you can set the poPageNums option to true. Consequently, on a document that has 12 pages, users can print for example pages from 4 through 8.

The Print Setup Dialog Box

 

Overview of the Print Setup Dialog Box

As opposed to directly printing a file, a user may want to perform some preliminary preparation on the file or the printer. Microsoft Windows provides another dialog box used to control printing. It is called Print Setup:

When using the Print Setup dialog box, the user must first select a printer. This is usually done already by the operating system that selects the default printer of the computer that called this dialog box. Otherwise, if there is more than one printer, the user can change it using the Name combo box.

The options of the Print Setup dialog box depend on the driver of the printer selected in the Name combo box.

The Print Setup dialog box allows the user to select a printer, if there is more than one, and to customize the appearance of the paper on which the document would be printed. On the Print Setup, the user can click the arrow of the Size combo box and select one of the configured sizes of paper:

If the printer has many trays, as indicated by the driver of the selected printer, the user can select which tray would be used when printing. As it happens, one printer can have only one tray while another printer can have 3, 5, or more:

If the desired printer is on a network, the user can click the Network button to locate it. He or she also has the option to print the document in Portrait (vertical) or in Landscape (horizontal) position.

Creation of the Print Setup Dialog box

In VCL applications, the Print Setup dialog box is provided by the TPrinterSetupDialog class. To make a Print Setup dialog available, at design time, from the Dialogs property sheet of the Tool Palette, click the PrintSetupDialog button and click on the form. Because the options of the Print Setup dialog box are configured and controlled by the driver of the printer selected, there is no significant configuration you need to perform.

 

Previous Copyright © 2005-2007 Yevol Next