Delphi - Visual Component Library PDF
Delphi - Visual Component Library PDF
Reference
Delphi for Windows
I n t r o d u c t i o n
Copyright
Agreement
This manual is a reference for the Delphi Visual Component Library (VCL) and the
Delphi run-time library. Use it when you want to look up the details of a particular VCL
object, component, variable, property, method, event, routine, or type and find out how
to use it.
Note See online Help for documentation of the Object Pascal Language Definition and
Reference.
Manual conventions
The printed manuals for Delphi use the typefaces and symbols described in
Table Intro.1 to indicate special text.
Table Intro.1 Typefaces and symbols in these manuals
Typeface or symbol Meaning
Monospace type Monospaced text represents text as it appears onscreen or in Object Pascal code.
It also represents anything you must type.
Boldface Boldfaced words in text or code listings represent Object Pascal reserved words
or compiler directives.
Italics Italicized words in text represent Object Pascal identifiers, such as variable or
type names. Italics are also used to emphasize certain words, such as new terms.
Keycaps This typeface indicates a key on your keyboard. For example, “Press Esc to exit a
menu.”
This symbol indicates a key, or important property, method, or event.
This symbol indicates a run-time only property, method or event.
Contacting Borland
The Borland Assist program offers a range of technical support plans to fit the different
needs of individuals, consultants, large corporations, and developers. To receive help
with this product send in the registration card and select the Borland Assist plan that
best suits your needs. North American customers can register by phone 24 hours a day
by calling 1-800-845-0147. For additional details on these and other Borland services, see
the Borland Assist Support and Services Guide included with this product.
Introduction 1
Delphi Visual Component Library
The VCL is made up of objects, most of which are also components. Using the objects
and components of VCL, you are unlimited in the range of Windows programs you can
develop rapidly. Delphi itself was built using VCL.
Delphi objects contain both code and data. The data is stored in the fields and properties
of the objects, and the code is made up of methods that act upon the field and property
values. All objects descend from the ancestor object TObject.
Components are visual objects that you can manipulate at design time. All components
descend from the TComponent object. To program with a component, this is the model
you will use most frequently:
1 Select a component from Delphi’s Component palette and add it to a form.
2 Set property values of the component using the Object Inspector.
3 Respond to events that might occur to the component at run time. To respond to an
event, you write code within an event handler. Your code modifies property values
and calls methods.
For detailed information on how to perform these three steps, see the Delphi User’s
Guide.
You can create your own objects and components by deriving them from the existing
Delphi objects and components. For information about writing your own components,
see the Delphi Component Writer’s Guide.
Note In addition to these objects, all VCL components also descend from TObject, although
not directly.
The TObject object introduces the following methods that all objects and components
inherit:
Table Intro.3 Object methods
ClassName ClassType Destroy
ClassParent Create Free
Introduction 3
Table Intro.4 VCL components (continued)
TButton TField TRadioButton
TBytesField TFileListBox TRadioGroup
TCheckBox TFilterComboBox TReplaceDialog
TColorDialog TFindDialog TReport
TComboBox TFloatField TSaveDialog
TCurrencyField TFontDialog TScreen
TDatabase TForm TScrollBar
TDataSource TGraphicField TScrollBox
TDateField TGroupBox TSession
TDateTimeField THeader TShape
TDBCheckBox TImage TSmallIntField
TDBComboBox TIntegerField TSpeedButton
TDBEdit TLabel TStoredProc
TDBGrid TListBox TStringField
TDBImage TMainMenu TStringGrid
TDBListBox TMaskEdit TTabbedNotebook
TDBLookupCombo TMediaPlayer TTable
TDBLookupList TMemo TTabSet
TDBMemo TMemoField TTimeField
TDBNavigator TMenuItem TTimer
TDBRadioGroup TNotebook TVarBytesField
TDBText TOLEContainer TWordField
TDDEClientConv TOpenDialog
Most components are available from the Component palette. You will not find the
following components on the Component palette, however:
Table Intro.5 Components not on the Component palette
TApplication TDateTimeField TScreen
TBCDField TField TSession
TBlobField TFloatField TSmallIntField
TBooleanField TGraphicField TStringField
TBytesField TIntegerField TTimeField
TCurrencyField TMemoField TVarBytesField
TDateField TMenuItem TWordField
The TComponent component introduces the following properties that all components
inherit:
Table Intro.6 Component properties
ComponentCount Components Owner
ComponentIndex Name Tag
In addition to the properties controls inherit from the TComponent component, the
TControl component introduces the following:
Table Intro.9 Control properties
Align Cursor ShowHint
BoundsRect Enabled Top
ClientHeight Height Visible
ClientOrigin Hint Width
ClientRect Left
ClientWidth Parent
Introduction 5
In addition to the methods controls inherit from the TComponent component, the
TControl component introduces the following methods:
Table Intro.10 Control methods
BeginDrag GetTextBuf Repaint
BringToFront GetTextLen ScreenToClient
ClientToScreen Hide SetBounds
ControlAtPos Invalidate SetTextBuf
Dragging Refresh Show
EndDrag SendToBack Update
In addition to the methods windowed controls inherit from the TControl component, the
TWinControl component introduces the following methods:
Table Intro.13 Windowed control methods
CanFocus Focused RemoveControl
ClientOrigin HandleAllocated ScaleBy
Create HandleNeeded ScrollBy
Destroy InsertControl SetFocus
Introduction 7
The following routines are used to display messages in dialog boxes:
Table Intro.16 Message dialog box routines
InputBox MessageDlg
InputQuery MessageDlgPos
The following routines are used to define menu command short cuts.
Table Intro.17 Menu shortcut routines
ShortCut ShortCutToText
ShortCutToKey TextToShortCut
The following routines are used to determine the parent form of components:
Table Intro.18 Parent form routines
GetParentForm ValidParentForm
The following routines are used to create graphical points and rectangles:
Table Intro.19 Point and rectangle routines
Bounds Point Rect
The following routines are used to control Object Linking and Embedding (OLE)
container applications:
Table Intro.20 OLE routines
BOLEMediumCalc LinksDlgEnabled ReleaseOLEInitInfo
ClearFormOLEDropFormats PasteSpecialDlg SetFormOLEDropFormats
InsertOLEObjectDlg PasteSpecialEnabled
LinksDlg RegisterFormAsOLEDropTarget
Library reference
The alphabetical reference following the sample entry in the next section contains a
detailed description of the Delphi VCL objects, components, variables, properties,
methods, events, routines, and types you use to develop Windows applications. The
reference also contains the procedures, functions, types, variables, and constants that
make up the Delphi run-time library and are declared in the System and SysUtils units.
These procedures and functions are useful routines that exist outside of the objects of
VCL. They are presented here so that you only need to search one reference source for
the information you need about programming Delphi applications.
Each alphabetically listed entry contains the declaration format and a description of the
entry. If the entry is an object, component, routine, or type, the unit that contains the
entry is listed at the beginning of the entry. (The unit that corresponds to a variable,
property, method, or event is the unit that contains the object or component to which the
entry belongs.) If the entry applies to specific objects or components, they are listed. The
Declaration
{ The declaration of the entry from the unit it occupies }
A description containing specific information about the entry.
Note Any special notes that apply to the entry
Example
A description of the example code that follows.
{ Example code which illustrates the use of the entry }
See also
Related entries that are also listed in the VCL Reference.
Introduction 9
10 Delphi Visual Component Library
Delphi Library Reference
Chapter 0
Abort method
Applies to
TPrinter object
Declaration
procedure Abort;
The Abort procedure terminates the printing of a print job, dropping all unprinted data.
The device is then set for the next print job. Use Abort to terminate the print job before it
completes; otherwise, use the EndDoc method.
To use the Abort method, you must add the Printers unit to the uses clause of your unit.
Example
The following code aborts a print job if the user presses Esc. Note that you should set
KeyPreview to True to ensure that the OnKeyDown event handler of Form1 is called.
procedure TForm1.FormKeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
begin
if (Key=VK_ESCAPE) and Printer.Printing then
begin
Printer.Abort;
MessageDlg('Printing aborted', mtInformation, [mbOK],0);
end;
end;
See also
BeginDoc method, EndDoc method, Printer variable, Printing property
Aborted property
Applies to
TPrinter object
Declaration
property Aborted: Boolean;
Run-time and read-only. The Aborted property determines if the user aborted the print
job, thereby calling the Abort method. If Aborted is True, the print job was aborted. If it is
False, the user did not abort the print job.
Example
The following code displays a dialog box if the print job was aborted:
if Printer.Aborted then
MessageDlg(‘The print job did not finish printing’), mtInformation, [mbOK], 0);
See also
Abort method, Printer variable, Printing property
AbortOnKeyViol property
Applies to
TBatchMove component
Declaration
property AbortOnKeyViol: Boolean;
If AbortOnKeyViol is True (the default) and an integrity (key) violation occurs during the
batch move operation, the Execute method will immediately terminate the operation. If
you prefer to have the operation continue, with all key violations posted to the key
violations table, set AbortOnKeyViol to False.
Note If you set AbortOnKeyViol to False, you should provide a KeyViolTableName to hold the
records with errors.
Example
BatchMove1.AbortOnKeyViol := False;
See also
KeyViolCount property, KeyViolTableName property
Declaration
property AbortOnProblem: Boolean;
If AbortOnProblem is True (the default) and it would be necessary to discard data from a
source record to place it into the Destination, the Execute method will immediately
terminate the batch move operation. If you prefer to have the operation continue, with
all problems posted to the problems table, set AbortOnProblem to False.
Note If you set AbortOnProblem to False, you should provide a ProblemTableName to hold the
records with problems.
Example
BatchMove1.AbortOnProblem := False;
See also
ProblemCount property, ProblemTableName property
Example
var
r: Real;
i: Integer;
begin
r := Abs(-2.3); { 2.3 }
i := Abs(-157); { 157 }
end;
Active property
Applies to
TOLEContainer, TQuery, TStoredProc, TTable components
Example
{ Close the dataset }
Table1.Active := False;
{ Open the dataset }
Table1.Active := True;
See also
AutoActivate property, InPlaceActive property, OnActivate event
ActiveControl property
Applies to
TForm, TScreen components
Declaration
property ActiveControl: TWinControl;
For forms, the ActiveControl property indicates which control has focus, or has focus
initially when the form becomes active. Your application can use the ActiveControl
property to access methods of the active control. Only one control, the active control, can
have focus at a given time in an application.
For the screen, ActiveControl is a read-only property. The value of ActiveControl is the
control that currently has focus on the screen.
Note When focus shifts to another control, the ActiveControl property is updated before the
OnExit event of the original control with focus occurs.
Example
The following event handler responds to timer events by moving the active control one
pixel to the right:
procedure TForm1.Timer1Timer(Sender: TObject);
begin
ActiveControl.Left := ActiveControl.Left + 1;
end;
See also
ActiveForm property, OnActiveControlChange event, OnEnter event, OnExit event
ActiveForm property
Applies to
TScreen component
Declaration
property ActiveForm: TForm;
Run-time and read only. The ActiveForm property indicates which form currently has
focus, or will have focus when the application becomes active again after another
Windows application has been active.
Example
This example changes the color of the current form.
procedure TForm1.Button1Click(Sender: TObject);
begin
Screen.ActiveForm := clBlue;
end;
See also
ActiveControl property, ActiveMDIChild property, OnActivate event,
OnActiveFormChange event, Screen variable
ActiveMDIChild property
Applies to
TForm component
Declaration
property ActiveMDIChild: TForm;
Run-time and read only. The value of the ActiveMDIChild property is the form that
currently has focus in an MDI application.
Example
This code uses a button on an MDI application. When the user clicks the button, the
active MDI child form turns blue.
procedure TForm1.Button1Click(Sender: TObject);
var
BlueForm: TForm;
begin
BlueForm := Form1.ActiveMDIChild;
BlueForm.Color := clBlue;
end;
See also
ActiveForm property, FormStyle property, MDIChildCount property, MDIChildren
property
Declaration
property ActivePage: string;
The ActivePage property determines which page displays in the notebook or tabbed
notebook control. The value of ActivePage must be one of the strings contained in the
Pages property.
Example
This example uses a notebook control and a button on the form. The notebook has
multiple pages, including one called Graphics options. When the user clicks the button,
the Graphics options page displays in the notebook control.
procedure TForm1.Button1Click(Sender: TObject);
begin
Notebook1.ActivePage := 'Graphics options’;
end;
See also
PageIndex property, TTabSet component
Add method
Applies to
TFieldDefs, TIndexDefs, TList, TStringList, TStrings objects; TMenuItem, TOutline
components
Example
This example adds a new object to a list in a list object:
type
TMyClass = class
MyString: string;
constructor Create(S: string);
end;
constructor TMyClass.Create(S: string);
begin
MyString := S;
end;
procedure TForm1.Button1Click(Sender: TObject);
var
MyList: TList;
MyObject, SameObject: TMyClass;
begin
MyList := TList.Create; { create the list }
try
MyObject := TMyClass.Create('Semper Fidelis!'); { create a class instance }
try
MyList.Add(MyObject); { add instance to list }
SameObject := TMyClass(MyList.Items[0]); { get first element in list }
MessageDlg(SameObject.MyString, mtInformation, [mbOk], 0); { show it }
finally
MyObject.Free;
end; { don't forget to clean up! }
finally
MyList.Free;
See also
Capacity property, Clear method, Delete method, Expand method, First method, IndexOf
method, Insert method, Last method, Remove method
Example
This code uses a button and a list box on a form. When the user clicks the button, the
code adds a new string to a list box.
procedure TForm1.Button1Click(Sender: TObject);
begin
ListBox1.Items.Add('New string');
end;
This code uses a list box, a button, and a label on a form. When the user clicks the
button, the code adds a new string to the list box and reports its position in the list box as
the caption of the label.
procedure TForm1.Button1Click(Sender: TObject);
var
Position: Integer;
begin
Position:= ListBox1.Items.Add('New item');
Label1.Caption := IntToStr(Position);
end;
See also
AddObject method, AddStrings method, Clear method, Delete method, Duplicates
property, Exchange method, Insert method, Items property, Lines property, Move method,
Sorted property
Example
This code adds a menu item to a File menu:
procedure Form1.Button1Click(Sender: TSender);
var
NewItem: TMenuItem;
begin
NewItem := TMenuItem.Create(Self);
NewItem.Caption := ‘New item’;
File.Add(NewItem);
end;
See also
Delete method, Insert method
For outlines
Declaration
function Add(Index: LongInt; const Text: string): LongInt;
The Add method adds an outline item (TOutlineNode object) to an outline. The value of
the Index parameter specifies where to add the new item. The Text parameter specifies
the Text property value of the new item. Add returns the Index property value of the
A
added item.
The added item is positioned in the outline as the last sibling of the outline item
specified by the Index parameter. The new item shares the same parent as the item
specified by the Index parameter. Outline items that appear after the added item are
moved down one row and reindexed with valid Index values. This is done automatically
unless BeginUpdate was called.
Note To add items to an empty outline, specify zero (0) as the Index parameter.
Example
The following code adds a new item at the top level of the outline. The new item is
identified by the text ‘New item’:
Outline1.Add(0, 'New item');
See also
AddChild method, AddChildObject method, AddObject method, Insert method, MoveTo
method
AddChild method
Applies to
TOutline component
Declaration
function AddChild(Index: LongInt; const Text: string): LongInt;
The AddChild method adds an outline item (TOutlineNode object) to an outline as a child
of an existing item. The value of the Index parameter specifies where to add the new
item. The Text parameter specifies the Text property value of the new item. AddChild
returns the Index property value of the added item.
The added item is positioned in the outline as the last child of the outline item specified
by the Index parameter. Outline items that appear after the added item are moved down
one row and reindexed with valid Index values. This is done automatically unless
BeginUpdate was called.
Note To add items to an empty outline, specify zero (0) as the Index parameter.
Example
The following code adds a new child to the selected item of the outline. The new item is
identified by the text ‘New child’:
Outline1.AddChild(Outline1.SelectedItem, 'New child');
See also
Add method, AddChildObject method, AddObject method, Insert method, MoveTo method
AddChildObject method
Applies to
TOutline component
Declaration
function AddChildObject(Index: LongInt; const Text: string; const Data: Pointer): LongInt;
The AddChildObject method adds an outline item (TOutlineNode object) containing data
to an outline as a child of an existing item. The value of the Index parameter specifies
where to add the new item. The Text parameter specifies the Text property value of the
new item. The Data parameter specifies the Data property value of the new item.
AddChild returns the Index property value of the added item.
The added item is positioned in the outline as the last child of the outline item specified
by the Index parameter. Outline items that appear after the added item are moved down
one row and reindexed with valid Index values. This is done automatically unless
BeginUpdate was called.
Note To add items to an empty outline, specify zero (0) as the Index parameter.
Example
The following code adds a new child to the selected item of the outline. The new item is
identified by the text ‘New child’. The TBitmap object named Bitmap1 is attached to the
new item:
Outline1.AddChildObject(Outline1.SelectedItem, 'New child', Bitmap1);
See also
Add method, AddChild method, AddObject method, Insert method, MoveTo method
AddFieldDesc method
Applies to
TFieldDefs object
AddIndex method
Applies to
TTable component
Declaration
procedure AddIndex(const Name, Fields: string; Options: TIndexOptions);
The AddIndex method creates a new index for the TTable. Name is the name of the new
index. Fields is a list of the fields to include in the index. Separate the field names by a
semicolon. Options is a set of values from the TIndexOptions type.
Example
Table1.AddIndex(‘NewIndex’, ‘CustNo;CustName’, [ixUnique, ixCaseInsensitive]);
See also
DeleteIndex method, IndexDefs property, IndexName property
AddObject method
Applies to
TStringList, TStrings objects; TOutline component
Example
This code adds the string ‘Orange’ and a bitmap of an orange to an owner-draw list box:
See also
Add method, AddStrings method, IndexOf method, IndexOfObject method, InsertObject
method, Objects property, Strings property
For outlines
Declaration
function AddObject(Index: LongInt; const Text: string; const Data: Pointer): LongInt;
The AddObject method adds an outline item (TOutlineNode object) containing data to an
outline. The value of the Index parameter specifies where to add the new item. The Text
parameter specifies the Text property value of the new item. The Data parameter
specifies the Data property value of the new item. Add returns the Index property value
of the added item.
The added item is positioned in the outline as the last sibling of the outline item
specified by the Index parameter. The new item shares the same parent as the item
specified by the Index parameter. Outline items that appear after the added item are
moved down one row and reindexed with valid Index values. This is done automatically
unless BeginUpdate was called.
Note To add items to an empty outline, specify zero (0) as the Index parameter.
Example
The following code defines a record type of TMyRec and a record pointer type of
PMyRec.
type
PMyRec = ^TMyRec;
TMyRec = record
FName: string;
LName: string;
end;
Assuming these types are used, the following code adds an outline node to Outline1. A
TMyRec record is associated with the added item. The FName and LName fields are
obtained from edit boxes Edit1 and Edit2. The Index parameter is obtained from edit box
Edit3. The item is added only if the Index is a valid value.
var
MyRecPtr: PMyRec;
OutlineIndex: LongInt;
See also
Add method, AddChild method, AddChildObject method, Insert method, MoveTo method
AddParam method
Applies to
TParams object
Declaration
procedure AddParam(Value: TParam);
AddParam adds Value as a new parameter to the Items property.
Example
{ Move all parameter info from Params2 to Params1 }
while Params2.Count <> 0 do
begin
{ Grab the first parameter from Params2 }
TempParam := Params2[0];
{ Remove it from Params2 }
Params2.RemoveParam(TempParam);
{ And add it to Params1 }
Params1.AddParam(TempParam);
end;
See also
RemoveParam method
AddPassword method
Applies to
TSession component
Declaration
procedure AddPassword(const Password: string);
The AddPassword method is used to add a new password to the current TSession
component for use with Paradox tables. When an application opens a Paradox table that
requires a password, the user will be prompted to enter a password unless the Session
has a valid password for the table.
Example
Session.AddPassword(‘ASecret’);
See also
Session variable
Example
var
P: Pointer;
begin
P := Addr(P); { Now points to itself }
end;
See also
Ofs function, Ptr function, Seg function
AddStrings method
Applies to
TStringList, TStrings objects
Declaration
procedure AddStrings(Strings: TStrings);
The AddStrings method adds a group of strings to the list of strings in a string or string
A
list object. The new strings are appended to the existing strings. Specify a string object
containing the list of strings you want added as the value of the Strings parameter.
Example
This code appends the contents of a file to the end of a memo control:
procedure TForm1.Button1Click(Sender: TSender);
var
Contents: TStringList;
begin
Contents.LoadFromFile(‘NEWSTUFF.TXT’);
Memo1.Lines.AddStrings(Contents);
finally
Contents.Free;
end;
This code adds the list of strings contained in ListBox1.Items to the end of the
ListBox2.Items list of strings:
procedure TForm1.Button1Click(Sender: TObject);
begin
ListBox2.Items.AddStrings(ListBox1.Items);
end;
See also
Add method, AddObject method, Strings property
AfterCancel event
Applies to
TTable, TQuery, TStoredProc components
Declaration
property AfterCancel: TDataSetNotifyEvent;
The AfterCancel event is activated when the dataset finishes a call to the Cancel method.
This event is the last action before Cancel returns to the caller. If the dataset is not in Edit
state or there are no changes pending, then Cancel will not activate the AfterCancel event.
By assigning a method to this property, you can take any special actions required by the
event.
See also
BeforeCancel event
AfterClose event
Applies to
TTable, TQuery, TStoredProc components
Declaration
property AfterClose: TDataSetNotifyEvent;
The AfterClose event is activated after a dataset is closed, either by calling the Close
method or by setting the Active property to False. This event is the last action before Close
returns to the caller. Typically, the AfterClose event handler closes any private lookup
tables opened by the BeforeOpen event.
By assigning a method to this property, you can take any special actions required by the
event.
See also
BeforeClose event
AfterDelete event
Applies to
TTable, TQuery, TStoredProc components
Declaration
property AfterDelete: TDataSetNotifyEvent;
The AfterDelete event is activated when the dataset finishes a call to the Delete method.
This event is the last action before Delete returns to the caller. When AfterDelete is called,
the deleted record has already been removed from the dataset, and the dataset cursor
will be positioned on the following record.
By assigning a method to this property, you can take any special actions required by the
event.
See also
BeforeDelete event
AfterEdit event
Applies to
TTable, TQuery, TStoredProc components
See also
BeforeEdit event
AfterInsert event
Applies to
TTable, TQuery, TStoredProc components
Declaration
property AfterInsert: TDataSetNotifyEvent;
The AfterInsert event is activated when a dataset finishes a call to the Insert or Append
methods. This event is the last action before Insert or Append returns to the caller.
Note This event occurs before a new record has been added to the component.
By assigning a method to this property, you can take any special actions required by the
event.
See also
BeforeInsert event
AfterOpen event
Applies to
TTable, TQuery, TStoredProc components
Declaration
property AfterOpen: TDataSetNotifyEvent;
The AfterOpen event is activated after a dataset is opened, either by calling the Open
method or by setting the Active property to True. This event is the last action before Open
returns to the caller.
By assigning a method to this property, you can take any special actions required by the
event.
See also
BeforeOpen event
AfterPost event
Applies to
TTable, TQuery, TStoredProc components
Declaration
property AfterPost: TDataSetNotifyEvent;
The AfterPost event is activated after a call to the Post method. This event is the last
action before Post returns to the caller.
If a TTable has a range filter (set with ApplyRange) in effect, and if the key value of the
newly posted record falls outside the range, then in the AfterPost event, the cursor will
not be positioned on the newly posted record.
By assigning a method to this property, you can take any special actions required by the
event.
See also
BeforePost event
AliasName property
Applies to
TDataBase component
Declaration
property AliasName: TSymbolStr;
AliasName is the name of an existing BDE alias defined with the BDE Configuration
Utility. This is where the TDatabase component gets its default parameter settings. This
property will be cleared if DriverName is set. If you try to set AliasName of a TDatabase for
which Connected is True, Delphi will raise an exception.
Example
Database1.AliasName := ‘DBDEMOS’;
Declaration
property Align: TAlign;
The Align property determines how the controls align within their container (or parent
control). These are the possible values:
Value Meaning
alNone The component remains where you place it in the form. This is the default value.
alTop The component moves to the top of the form and resizes to fill the width of the form. The
height of the component is not affected.
alBottom The component moves to the bottom of the form and resizes to fill the width of the form.
The height of the component is not affected.
alLeft The component moves to the left side of the form and resizes to fill the height of the form.
The width of the component is not affected.
alRight The component moves to the right side of the form and resizes to fill the height of the
form. The width of the component is not affected.
alClient The component resizes to fill the client area of a form. If a component already occupies
part of the client area, the component resizes to fit within the remaining client area.
Example
This example moves a panel control named Panel1 to the bottom of the form and resizes
it to fill the width of the form:
procedure TForm1.Button1Click(Sender: TObject);
begin
Panel1.Align := alBottom;
end;
See also
Alignment property
Alignment property
Applies to
TBCDField, TBooleanField, TCheckBox, TCurrencyField, TDateField, TDateTimeField,
TDBCheckBox, TDBMemo, TDBText, TFloatField, TIntegerField, TLabel, TMemo, TPanel,
TPopupMenu, TRadioButton, TSmallintField, TStringField, TTimeField, TWordField
components
Value Meaning
taLeftJustify Align text to the left side of the control
taCenter Center text horizontally in the control
taRightJustify Align text to the right side of the control
Example
This code aligns text to the right side of a label named Label1 in response to a click on a
button named RightAlign:
procedure TForm1.RightAlignClick(Sender: TObject);
begin
Label1.Alignment := taRightJustify;
end;
See also
Caption property, Text property
Example
This code makes the check box two-dimensional and puts the check box on the left side
of the text:
procedure TForm1.Button1Click(Sender: TObject);
begin
CheckBox1.Ctl3D := False;
CheckBox1.Alignment := taLeftJustify;
end;
See also
Caption property
Value Meaning
paLeft The pop-up menu appears with its top left corner under the mouse pointer.
paCenter The pop-up menu appears with the top center of the menu under the mouse pointer.
paRight The pop-up menu appears with its top right corner under the mouse pointer.
Example
This example uses a pop-up menu component and a button on a form. The code places
the top right corner of a pop-up menu under the mouse pointer when the menu
appears:
procedure TForm1.AlignPopupMenuClick(Sender: TObject);
begin
PopupMenu1.Alignment := paRight;
end;
See also
AutoPopup property, OnPopup event
See also
ReAllocMem function
AllowAllUp property
Applies to
TSpeedButton component
Declaration
property AllowAllUp: Boolean;
The AllowAllUp property determines if all speed buttons in a group this speed button
belongs to can be unselected (in their up state) at the same time. AllowAllUp should be
used only with speed buttons in a group (that is, the value of the button’s GroupIndex
property is not zero). See the GroupIndex property for information on how to create a
group of speed buttons. If GroupIndex is zero, AllowAllUp has no effect.
If AllowAllUp is True, all of the speed buttons in a group can be unselected. All buttons
can appear in their up state.
If AllowAllUp is False, one of the speed buttons belonging to a group must be selected (in
its down state) at all times. Clicking a down button won’t return the button to its up
state. The button only becomes unselected when the user clicks one of the other buttons
in the group. In such a group, one button must always be selected. Determine which
speed button will be initially down by setting its Down property to True.
The default value is False.
Changing the value of the AllowAllUp property for one speed button in a group changes
the AllowAllUp value for all buttons in the group.
You can use AllowAllUp with a single bitmap button in its own group (with a
A
GroupIndex value greater than 0) so that the button can be selected and remain selected
until the user clicks the button again—at which time it becomes unselected. In other
words, the button can work much like a check box. To make a single speed button
behave this way, set its GroupIndex property to a value greater than 0 (but different from
any other GroupIndex value of any other speed buttons you have), and set AllowAllUp to
True.
Example
In this example, there are three speed buttons on a form. All three belong to the same
group as all three have a GroupIndex value of 1. This line of code changes the AllowAllUp
property to True for all three speed buttons, so it’s possible that all the speed buttons in
the group can be unselected at the same time:
SpeedButton3.AllowAllUp := True;
See also
Down property, Glyph property, GroupIndex property
AllowGrayed property
Applies to
TCheckBox, TDBCheckBox components
Declaration
property AllowGrayed: Boolean;
The value of the AllowGrayed property determines if a check box can have two or three
possible states. If AllowGrayed is False, the default value, clicking a check box alternately
checks and unchecks it. If AllowGrayed is True, clicking a check box either checks, grays,
or unchecks it.
Example
This example uses a check box on a form. When the application runs, the check box is
initially checked. When the user clicks it, the check box is unchecked. Clicking it again
grays the check box.
procedure TForm1.FormCreate(Sender: TObject);
begin
CheckBox1.AllowGrayed := True;
CheckBox1.State := cbChecked;
end;
See also
Checked property, State property
AllowInPlace property
Applies to
TOLEContainer component
Declaration
property AllowInPlace: Boolean;
The AllowInPlace property specifies whether an OLE object can be activated in place. If
AllowInPlace is True, in-place activation is allowed. If AllowInPlace is False, in-place
activation is not allowed and the OLE object is activated in its own window (OLE 1.0-
style).
Note To support in-place activation, the OLE container application must include a
TMainMenu component.
Example
The following code sets AllowInPlace to False.
OLEContainer1.AllowInPlace := False;
See also
AutoActivate property
AllowResize property
Applies to
THeader component
Declaration
property AllowResize: Boolean;
The value of the AllowResize property determines if the user can modify the size of the
header at run time with the mouse. If AllowResize is False, the sections within a header
can’t be resized. If AllowResize is True, clicking a border of a header section and dragging
it left or right changes the width of the section. The default value is True.
Example
The following code allows the resizing of the sections of Header1.
Header1.AllowResize := True;
See also
OnSized event, Sections property, SectionWidth property, Sizing event
See also
AnsiCompareText function
See also
AnsiCompareStr function
See also
AnsiUpperCase function, LowerCase function
AnsiToNative function DB
Declaration
function AnsiToNative(Locale: TLocale; const AnsiStr: string; NativeStr: PChar;
MaxLen: Word): PChar;
The AnsiToNative function translates the ANSI characters in AnsiStr (or the first MaxLen
characters) to the native character set according to Locale by calling DBIAnsiToNative.
The translated characters are returned in NativeStr with a null terminator. AnsiToNative
returns NativeStr.
See also
AnsiLowerCase function, UpperCase function
Append method
Applies to
TTable, TQuery, TStoredProc components
Declaration
procedure Append;
The Append method moves the cursor to the end of the dataset, puts the dataset into
Insert state , and opens a new, empty record. When an application calls Post, the new
record will be inserted in the dataset in a position based on its index, if defined. To
discard the new record, use Cancel.
This method is valid only for datasets that return a live result set.
Note For indexed tables, the Append and Insert methods will both put the new record in the
correct location in the table, based on the table’s index. If no index is defined on the
underlying table, then the record will maintain its position—Append will add the record
to the end of the table, and Insert will insert it at the current cursor position. In either
case, posting a new record may cause rows displayed in a data grid to change as the
dataset follows the new row to its indexed position and then fetches data to fill the data
grid around it.
Example
with Table1 do
begin
Append;
FieldByName(‘CustNo’).AsString := ‘9999’;
{ Fill in other fields here }
if { you are sure you want to do this} then Post
else { if you changed your mind } Cancel;
end.
Example
var F: TextFile;
begin
if OpenDialog1.Execute then { Bring up open file dialog }
begin
AssignFile(F, OpenDialog1.FileName);
{ Open file selected in dialog }
Append(F); { Add more text onto end }
Writeln(F, 'appended text');
CloseFile(F); { Close file, save changes }
end;
end;
See also
AssignFile procedure, FileClose procedure, Reset procedure, Rewrite procedure
AppendRecord method
Applies to
TTable, TQuery, TStoredProc components
Declaration
procedure AppendRecord(const Values: array of const);
The AppendRecord method appends a new record to the dataset using the field values
passed in the Values parameter. The assignment of the elements of Values to fields in the
record is sequential; the first element is assigned to the first field, the second to the
second, etc. The number of field values passed in Values may be fewer than the number
of actual fields in the record; any remaining fields are left unassigned and are NULL.
The type of each element of Values must be compatible with the type of the field in that
the field must be able to perform the assignment using AsString, AsInteger, and so on,
according the type of the Values element.
This method is valid only for datasets that return a live result set.
Note For indexed tables, the AppendRecord and InsertRecord methods will both put the new
record in the correct location in the table, based on the table’s index. If no index is
defined on the underlying table, then the record will maintain its position—
AppendRecord will add the record to the end of the table, and InsertRecord will insert it at
the current cursor position. In either case, posting a new record in a data grid may cause
all the rows before and after the new record to change as the dataset follows the new
row to its indexed position and then fetches data to fill the grid around it.
Example
Table1.AppendRecord([9999, ‘Doe‘, ‘John‘]);
See also
TField component.
Example
This code displays the name of your project in an edit box:
procedure TForm1.Button1Click(Sender: TObject);
begin
Edit1.Text := Application.Title;
end;
See also
Icon property, Run method, Title property
ApplyFilePath method
Applies to
TFileListBox component
Declaration
procedure ApplyFilePath(const EditText: string);
ApplyFileEditText is intended to be used in a dialog box that approximates the utility and
behavior of an Open dialog box. Such a dialog box would contain a file list box
(TFileListBox), a directory list box (TDirectoryListBox), a drive combo box
(TDriveComboBox), a filter combo box TFilterComboBox, a label, and an edit box where
the user can type a file name including a full directory path. When the user then chooses
the OK button, you would like all the controls to update with the information the user
entered in the edit box. For example, you would want the directory list box to change to
the directory specified in the path the user typed, and you want the drive combo box to
change to the correct drive if the path included a different drive letter.
If the file list box, directory list box, drive combo box, filter combo box, label, and edit
box are connected using the FileEdit, FileList, DirLabel, and DirList properties, your
application can call ApplyFilePath to update the controls with the text the user entered in
the edit box.
The user can enter any of these strings in the edit box: a file name, with or without a
path, a drive only, a drive and directory only, relative paths, or a file mask using
wildcard characters. In all cases, the ApplyFilePath method updates the controls as you
would expect. For example, if the user includes a directory name, the directory list box
makes that directory the current one.
The EditText parameter is the text within the edit box.
Example
This example uses a file list box, a directory list box, a filter combo box, a drive combo
box, a label, an edit box, and a button on a form. When the user runs the application and
enters a path or file name in the edit box, all the controls update:
procedure TForm1.FormCreate(Sender: TObject);
begin
FileListBox1.FileEdit := Edit1;
FilterComboBox1.FileList := FileListBox1;
DirectoryListBox1.FileList := FileListBox1;
DirectoryListBox1.DirLabel := Label1;
DriveComboBox1.DirList := DirectoryListBox1;
Button1.Default := True;
end;
procedure TForm1.Button1Click(Sender: TObject);
begin
FileListBox1.ApplyFilePath(Edit1.Text);
end;
See also
Directory property, Drive property
ApplyRange method
Applies to
TTable component
Declaration
procedure ApplyRange;
The ApplyRange method is used to apply the start and end ranges established with the
SetRangeStart and SetRangeEnd methods or the EditRangeStart and EditRangeEnd
methods. This will filter the set of records from the database table accessible to the
application.
Note When comparing fields for range purposes, a NULL field is always less than any other
possible value.
Example
{ Limit the range from ‘Goleta’ to ‘Santa Barbara’}
with Table1 do
begin
EditRangeStart; { Set the beginning key }
See also
CancelRange method, KeyExclusive property, KeyFieldCount property, SetRange method
Arc method
Applies to
TCanvas object
Declaration
procedure Arc(X1, Y1, X2, Y2, X3, Y3, X4, Y4: Integer);
The Arc method draws an arc on the canvas along the perimeter of the ellipse bounded
by the specified rectangle. Coordinates (X1, Y1 and X2, Y2) define the enclosing
rectangle for the arc. The arc starts at the intersection of the ellipse edge and the line
from the center of the ellipse to the specified starting point (X3, Y3). The arc is drawn
counterclockwise until it reaches the position where the ellipse edge intersects the line
from the center of the ellipse to the specified ending point (X4, Y4).
Example
The following lines of code draw the top quarter of an arc bounded by the current
window:
TForm1.FormPaint(Sender: TObject);
var
R: TRect;
begin
R := GetClientRect; {Gets the rectangular coordinates of the current window}
Canvas.Arc(R.Left, R.Top, R.Right, R.Bottom, R.Right, R.Top, R.Left, R.Top);
end;
See also
Chord method, Draw method, DrawFocusRect method, Ellipse method, Pie method
You can calculate other trigonometric functions using Sin, Cos, and ArcTan in the
following expressions:
Tan(x) = Sin(x) / Cos(x)
ArcSin(x) = ArcTan (x/sqrt (1–sqr (x)))
ArcCos(x) = ArcTan (sqrt (1–sqr (x)) /x)
Example
var
R: Real;
begin
R := ArcTan(Pi);
end;
See also
Cos function, Sin function
ArrangeIcons method
Applies to
TForm component
Declaration
procedure ArrangeIcons;
The ArrangeIcons method arranges the icons of minimized forms so that they are evenly
spaced and don’t overlap. The ArrangeIcons method applies only to forms that are MDI
parent forms (have a FormStyle property value of fsMDIForm).
Example
This code runs when the user chooses a menu item called Window|Arrange Icons:
procedure TForm1.WindowArrangeIconsClick(Sender: TObject);
begin
Form1.ArrangeIcons;
end;
See also
Cascade method, Next method, Previous method, Tile method
AsBCD property
Applies to
TParam object
See also
TFieldType type
AsBoolean property
Applies to
TParam object; TBooleanField, TStringField components
Example
if Table1.FieldByName('BackOrdered').AsBoolean then ...
AsCurrency property
Applies to
TParam object
Declaration
property AsCurrency: Double;
Assigning a value to the AsCurrency property sets the DataType property to ftCurrency
and saves the value as the current data for the parameter. Accessing the AsCurrency
property attempts to convert the current data to a Double value and returns that value.
See also
TFieldType type
AsDate property
Applies to
TParam object
Declaration
property AsDate: TDateTime;
Assigning a value to the AsDate property sets the DataType property to ftDate and saves
the value as the current data for the parameter. Accessing the AsDate property attempts
to convert the current data to a TDateTime value and returns that value.
See also
StrToDateTime function, TFieldType type
AsDateTime property
Applies to
TParam object; TDateField, TDateTimeField, TStringField, TTimeField components
See also
StrToDateTime function, TFieldType type
Example
The following statement converts a string to a date for insertion into a date field:
Table1.FieldByName(TimeStamp).AsDateTime := StrToDateTime(Now);
See also
DateToStr function, StrToDate function, StrToDateTime function, DateTimeToStr function,
TimeToStr function, StrToTime function, Value property
AsFloat property
Applies to
TParam object; TBCDField, TCurrencyField, TFloatField, TStringField components
See also
TFieldType type
See also
FloatToStr function, StrToFloat function
AsInteger property
Applies to
TParam object; TIntegerField, TSmallintField, TStringField, TWordField components
See also
TFieldType type
See also
Data Access Components Hierarchy, IntToStr function, StrToInt function, Value
property
Example
The following code copies the bitmap of a speed button named SpeedButton1 to the
Clipboard:
Clipboard.Assign(SpeedButton1.Glyph);
See also
AsText property, Clipboard variable, HasFormat property
Declaration
procedure Assign(FieldDefs: TFieldDefs);
Assign creates a new set of TFieldDef objects in Items from the FieldDefs parameter. Any
previously entries in Items are freed.
Examples
{ Copy one date-time field to another }
DateTimeField1.Assign(DateTimeField2);
{ Copy a graphic field to a blob field }
BlobField1.Assign(GraphicField1);
{Copy strings in a TMemo to a TMemoField}
MemoField1.Assign(Memo1.Lines);
See also
DataType property, Size property
Example
{ Copy the CustNo parameter from Query1 to Query2 }
Example
var SavedParams: TParams;
...
{ Initialize SavedParams }
SavedParams := TParams.Create;
{ Save the parameters for Query1 }
SavedParams.Assign(Query1.Parameters);
{ Do something with Query1 }
...
{ Restore the parameters to Query1 }
Query1.Parameters.Assign(SavedParams);
SavedParams.Free;
See also
AssignValues method
If Destination is a property of some object, however, and that property is not a reference
to another object (such as the ActiveControl property of a form, or the DataSource
property of a data-aware control), then the statement "Destination := Source" is the same
as "Destination.Assign(Source)". Consider these statements:
Button1.Font := Button2.Font;
ListBox1.Items := Memo1.Lines;
Table1.Fields[0] := Query1.Fields[2];
They correspond to these statements:
Button1.Font.Assign(Button2.Font);
ListBox1.Items.Assign(Memo1.Lines);
Table1.Fields[0].Assign(Query1.Fields[2]);
The actions performed by Assign depend on the actual types of Destination and Source.
For example, if Destination and Source are string objects (TStrings), the strings contained
in Source are copied into Destination. Likewise, if Destination and Source are bitmaps
(TBitmap), the bitmap contained in Source is copied into Destination.
Although the compiler allows any two TPersistent objects to be used in a call to Assign,
the call succeeds at run time only if the objects involved "know" how to perform an
assignment. For example, if Destination is a button (TButton) and Source is an edit box
(TEdit), the call to Assign raises an EConvertError exception at run time.
An object of one type can always be assigned to another object of the same type. In
addition, Assign supports the following special cases:
• If Destination is of type TPicture then Source can be of type TBitmap, TIcon, or TMetafile.
• If Destination is of type TBitmap, TIcon, or TMetafile then Source can be of type TPicture
if the Graphic property of the picture is of the same type as Destination.
• If Destination is of type TBlobField then Source can be of type TBitmap, TPicture, or
TStrings.
Example
The following code changes the properties of a label’s font so that they match the
properties of the button’s font when the user clicks the button:
procedure TForm1.Button1Click(Sender: TObject);
begin
Label1.Font.Assign(Button1.Font);
end;
AssignCrt works exactly like the Assign standard procedure except that no file name is
A
specified. Instead, the text file associates with the CRT window, which emulates a text-
based CRT in the Windows environment. Subsequent Write and Writeln operations on
the file write to the CRT window, and Read and Readln operations read from the CRT
window.
This allows faster output (and input) than would normally be possible using standard
output (or input).
See also
AssignFile procedure, Read procedure, Readln procedure, Write procedure, Writeln
procedure
Example
var P: Pointer;
begin
P := nil;
if Assigned (P) then Writeln ('You won''t see this');
P := @P;
if Assigned (P) then Writeln ('You''ll see this');
end;
AssignField method
Applies to
TParam object
Declaration
procedure AssignField(Field: TField);
The AssignField method transfers the DataType value and Name from Field. Use
AssignField to set a parameter from a TField component.
Example
{ Copy the CustNo field value from Query1 to the CustNo parameter of Query2 }
Query2.ParamByName(‘CustNo’).AssignField(Query1.FieldNyName(‘CustNo’));
Example
var
F: TextFile;
S: string;
begin
if OpenDialog1.Execute then { Display Open dialog box }
See also
Append procedure, FileClose procedure, Reset procedure, Rewrite procedure
Example
This code prints a line of text on the printer when the user clicks the button on the form:
procedure TForm1.Button1Click(Sender: TObject);
var
MyFile: TextFile;
begin
AssignPrn(MyFile);
Rewrite(MyFile);
Writeln(MyFile, ‘Print this text’);
System.CloseFile(MyFile);
end;
Example
var
P: PString;
begin
P := NewStr('First string'); { Allocate and point to 'First string' }
AssignStr(P, 'Second string'); { Dispose of 'First string', allocate and point to }
{ 'Second string' }
DisposeStr(P); { Dispose of 'Second string' }
end;
See also
DisposeStr procedure
AssignValue method
Applies to
TBCDField, TBlobField, TBooleanField, TBytesField, TCurrencyField, TDateField,
TDateTimeField, TFloatField, TGraphicField, TIntegerField, TMemoField, TSmallintField,
TStringField, TTimeField, TVarBytesField, TWordField components
Declaration
procedure AssignValue(const Value: TVarRec);
The AssignValue method sets the field to Value using one of the AsInteger, AsBoolean,
AsString or AsFloat properties, depending on the type of Value. If Value is of type TObject
or a TObject descendant, AssignValue uses the Assign method to transfer the information.
Example
Field1.AssignValue(‘new string’);
AssignValues method
Applies to
TParams object
Declaration
procedure AssignValues(Value: TParams);
For each entry in Items, the AssignValues method attempts to find a parameter with the
same Name property in Value. If successful, the parameter information (type and current
data) from the Value parameter is assigned to the Items entry. Entries in Items for which
no match is found are left unchanged.
AsSmallInt property
Applies to
TParam object
Declaration
procedure SetAsSmallInt(Value: Longint);
Assigning a value to the AsSmallInt property sets the DataType property to fsSmallInt
and save the value as the current data for the parameter. Accessing the AsSmallInt
property attempts to convert the current data to a SmallInt value and returns that value.
AsString property
Applies to
TParam object; TBCDField, TBlobField, TBooleanField, TBytesField, TCurrencyField,
TDateField, TDateTimeField, TFloatField, TGraphicField, TIntegerField, TMemoField,
TSmallintField, TStringField, TTimeField, TVarBytesField, TWordField components
See also
DateToStr function, DateTimeToStr function, FloatToStr function, IntToStr function,
TFieldType type, TimeToStr function
AsText property
Applies to
TClipboard object
Declaration
property AsText: String;
Run-time only. The AsText property returns the current contents of the Clipboard as a
string. The Clipboard must contain a string or an exception occurs.
You can also use the AsText property to place a copy of a string on the Clipboard. Assign
a string as the value of AsText.
The string value of the AsText property is limited to 255 characters. If you need to set
A
and retrieve more than 255 characters, use the SetTextBuf and GetTextBuf Clipboard
methods.
If the Clipboard contains a string, this expression is True:
Clipboard.HasFormat(CF_TEXT)
Example
The following code retrieves the contents of the Clipboard as a string and displays the
value in a label:
begin
Label1.Caption := Clipboard.AsText;
end;
See also
Clipboard variable, HasFormat method
AsTime property
Applies to
TParam object
Declaration
property AsTime: TDateTime;
Assigning a value to the AsTime property sets the DataType property to ftTime and saves
the value as the current data for the parameter. Accessing the AsTime property attempts
to convert the current data to a TDateTime value and returns that value.
See also
StrToDateTime function, TDateTime type, TFieldType type
AsWord property
Applies to
TParam object
Declaration
property AsWord: Longint;
Assigning a value to the AsWord property sets the DataType property to ftWord and
saves the value as the current data for the parameter. Accessing the AsWord property
attempts to convert the current data to a Longint value and returns that value.
See also
TFieldType type
AutoActivate property
Applies to
TOLEContainer component
Declaration
property AutoActivate: TAutoActivate;
AutoActivate determines how an object in an OLE container can be activated. These are
the possible values:
Value Meaning
aaManual The OLE object must be manually activated. To activate the OLE object manually,
set the Active property to True.
aaGetFocus The user activates the OLE object by clicking the OLE container or pressing Tab
until focus shifts to the OLE container. If the OLE container has a TabOrder of 0,
the OLE container initially receives focus but the OLE object won’t be activated.
aaDoubleClick The user activates the OLE object by double-clicking the OLE container, or
pressing Enter when the container has focus. An OnDblClick event is generated
immediately after the OLE server application is activated.
Example
The following code sets the activation method of OLEContainer1 to aaManual, then
activates OLEContainer1:
OLEContainer1.AutoActivate := aaManual;
OLEContainer1.Active := True;
See also
OnActivate event
AutoCalcFields property
Applies to
TTable, TQuery, TStoredProc components
Declaration
property AutoCalcFields: Boolean;
The AutoCalcFields property determines when OnCalcFields is called. OnCalcFields is
always called whenever an application retrieves a record from the database. If
AutoCalcFields is True, then OnCalcFields is called also whenever a field in a dataset is
edited.
If AutoCalcFields is True, OnCalcFields should not perform any actions that modify the
A
dataset (or the linked dataset if it is part of a master-detail relationship), because this can
lead to recursion. For example, if OnCalcFields performs a Post, and AutoCalcFields is
True, then OnCalcFields will be called again, leading to another Post, and so on.
AutoDisplay property
Applies to
TDBImage, TDBMemo component
Declaration
property AutoDisplay: Boolean;
The value of the AutoDisplay property determines whether to automatically display the
contents of a memo or graphic BLOB in a database memo (TDBMemo) or database
image (TDBImage) control.
If AutoDisplay is True (the default value), the control automatically displays new data
when the underlying BLOB field changes (such as when moving to a new record).
If AutoDisplay is False, the control clears whenever the underlying BLOB field changes.
To display the data, the user can double-click on the control or select it and press Enter.
In addition, by calling the LoadMemo method of a database memo or the LoadPicture
method of a database image you can ensure that the control is showing data.
You might want to change the value of AutoDisplay to False if the automatic loading of
BLOB fields seems to take too long.
Example
The following code displays the text BLOB in DBMemo1.
DBMemo1.AutoDisplay := True;
See also
LoadMemo method, LoadPicture method
AutoEdit property
Applies to
TDataSource component
Declaration
property AutoEdit: Boolean;
AutoEdit determines if data-aware controls connected to TDataSource automatically
place the current record into edit mode by calling the table’s Edit method when the user
begins typing within one of them. AutoEdit is True by default; set it to False to protect the
data from being unintentionally modified. When AutoEdit is False, you can still call the
Edit method to modify a field.
AutoEnable property
Applies to
TMediaPlayer component
Declaration
property AutoEnable: Boolean;
The AutoEnable property determines whether the media player automatically enables
and disables individual buttons in the component.
If AutoEnable is True, the media player automatically enables or disables its control
buttons. The media player determines which buttons to enable or disable by the current
mode specified in the Mode property, and the current multimedia device type specified
in the DeviceType property.
AutoEnable overrides the EnabledButtons property. The buttons enabled or disabled
automatically by the media player supersede any buttons enabled or disabled with
EnabledButtons.
If AutoEnable is False, the media player does not enable or disable buttons. You must
enable or disable buttons with the EnabledButtons property.
The following table shows whether buttons are automatically enabled or disabled for
each device mode:
Example
The following code causes all of the buttons of MediaPlayer1 to become disabled when a
bitmap button is clicked:
procedure TForm1.BitBtn1Click(Sender: TObject);
begin
with MediaPlayer1 do begin
AutoEnable := False;
See also
AutoOpen property
AutoMerge property
Applies to
TMainMenu component
Declaration
property AutoMerge: Boolean;
The AutoMerge property determines if the main menus (TMainMenu) of forms other
than the main form merge with the main menu of the main form in non-MDI
applications at run time. The default value is False. To merge the form’s menus with the
main menu in the main form, set the AutoMerge property of each main menu you want
merged to True. Make sure that the AutoMerge property of the main menu you are
merging with other menus remains False. How menus merge depends on the value of
the GroupIndex property for each menu item.
If the application is an MDI application (the FormStyle properties are set so the main
form is a parent form and subsequent forms are child forms), menu merging occurs
automatically and you don’t need to use the AutoMerge property. In an MDI application,
you should be sure that the AutoMerge value for the main menu of the parent form is
False, or else the menu bar of the parent form disappears when a child form appears.
Example
This example uses two forms with a main menu and a button on each form. Using the
Object Inspector, set the GroupIndex value for each menu item on the menu bar in the
second form to a number greater than 0. When the application runs and the user clicks
the button on the first form, the main menu on the second form merges with the main
menu of the first form. When the user clicks the button on the second form, the form
closes.
procedure TForm1.Button1Click(Sender: TObject);
begin
Form2.MainMenu1.AutoMerge := True;
Form2.Show;
end;
This is the code for the button-click event handler on the second form:
procedure TForm2.Button1Click(Sender: TObject);
begin
Close;
end;
To run this example, you must add Unit2 to the uses clause of Unit1.
See also
GroupIndex property, Merge method, Unmerge method
AutoOpen property
Applies to
TMediaPlayer component
Declaration
property AutoOpen: Boolean;
The AutoOpen property determines if the media player is opened automatically when
the application is run. If AutoOpen is True, the media player attempts to open the
multimedia device specified by the DeviceType property (or FileName if DeviceType is
dtAutoSelect) when the form containing the media player component is created at run
time. If AutoOpen is False, the device must be opened with a call to the Open method.
AutoOpen defaults to True.
If an error occurs when opening the device, an exception of type EMCIDeviceError is
raised which contains the error message. Upon completion, a numerical error code is
stored in the Error property, and the corresponding error message is stored in the
ErrorMessage property.
The Wait property determines whether control is returned to the application before
opening the multimedia device. The Notify property determines whether opening the
device generates an OnNotify event.
Example
The following code opens MediaPlayer1 if AutoOpen was not set to True. This code
assumes that an appropriate value was specified for FileName at design time.
with MediaPlayer1 do
if not AutoOpen then
Open;
See also
Close method
AutoPopup property
Applies to
TPopupMenu component
Example
The following prevents the pop-up menu from appearing when the user clicks the right
mouse button:
PopupMenu1.AutoPopup := False;
See also
OnPopup event, Popup method
AutoRewind property
Applies to
TMediaPlayer component
Declaration
property AutoRewind: Boolean;
The AutoRewind property determines if the media player control rewinds before playing
or recording.
If AutoRewind is True and the current position is at the end of the medium, Play or
StartRecording moves the current position to the beginning of the medium before
playing or recording. If AutoRewind is False, the user must click the Prev button or your
code must call Previous to move to the beginning.
Note If values have been assigned to StartPos or EndPos or if the multimedia device uses
tracks, AutoRewind has no effect on playing or recording. When you call Play or
StartRecording, the current position remains at the end of the medium.
Example
The following code plays MediaPlayer. If AutoRewind is False, Previous is called to rewind
after Play is finished.
MediaPlayer.Wait := True;
MediaPlayer.Play;
if not MediaPlayer.AutoRewind then MediaPlayer.Previous;
See also
Rewind method
AutoScroll property
Applies to
TForm, TScrollBox, TTabSet components
Example
This code displays scroll buttons in the tab set control if all the tabs aren’t visible:
TabSet11.AutoScroll := True;
See also
FirstIndex property, TabIndex property
Example
This example uses a label on a form. When the form becomes active, the label displays a
message informing the user whether scroll bars will be available if the form is resized so
that not all controls are fully visible.
procedure TForm1.FormActivate(Sender: TObject);
begin
See also
HorzScrollBar property, ScrollInView method, VertScrollBar property
AutoSelect property
Applies to
TDBEdit, TDBLookupCombo, TEdit, TMaskEdit components
Declaration
property AutoSelect: Boolean;
The value of the AutoSelect property determines if the text in the edit box or combo box
is automatically selected when the user tabs to the control. If AutoSelect is True, the text is
selected. If AutoSelect is False, the text is not selected.
The default value is True.
Example
This example uses an edit box and a check box on a form. Set the caption of the check
box to ‘AutoSelect text’. When the user checks the check box, text is automatically
selected each time the user tabs to the edit box. If the user unchecks the check box, text is
no longer selected automatically when the user tabs to the edit box.
procedure TForm1.CheckBox1Click(Sender: TObject);
begin
if CheckBox1.Checked then
Edit1.AutoSelect := True
else
Edit1.AutoSelect := False;
end;
end;
See also
AutoSize property, SelLength property, SelStart property, SelText property, Text property
AutoSize property
Applies to
TDBEdit, TDBText, TEdit, TImage, TLabel, TMaskEdit, TOLEContainer components
The AutoSize property determines if the component automatically resizes to match the
size of its contents.
For images
Declaration
property AutoSize: Boolean;
When the AutoSize property is True, the image control resizes to accommodate the
image it contains (specified by the Picture property). When AutoSize is False, the image
control remains the same size, regardless of the size of the image. If the image control is
smaller than the image, only the portion of the picture that fits inside the image
component will be visible.
The default value is False.
Note You must remember to set the AutoSize property to True before loading the picture, or
AutoSize has no effect.
To resize the image to fill an image control completely when the control is larger than
the native size of the image, use the Stretch property.
Example
This example uses an image control and a button. Resize the image control so that it is
too small to display the entire bitmap. When the user clicks the button, the bitmap is
loaded into the image control, and the image control resizes to display the bitmap in its
entirety.
procedure TForm1.Button1Click(Sender: TObject);
begin
Image1.AutoSize := True;
Image1.Picture.LoadFromFile('c:\windows\arches.bmp');
end;
See also
LoadFromFile method, Stretch property
See also
Font property
Example
The following code keeps the size of the label control constant, even though the length
of the label’s caption changes. As a result, the caption of the label is probably too long to
display in the label when the user clicks the button:
procedure TForm1.Button1Click(Sender: TObject);
begin
Label1.AutoSize := False;
Label1.Caption := 'This string is too long as the caption of this label';
end;
See also
WordWrap property
Declaration
property AutoSize: Boolean;
Autosize determines whether the OLE container automatically resizes to the size of the
OLE object it contains.
If Autosize is True, the OLE container adopts the shape of the OLE object at run time. If
the user activates the object and changes its size, the OLE container resizes to the new
size. Setting Autosize to True may unintentionally cause the OLE container to resize to a
shape that exists outside the client area of the form or over other controls.
If Autosize is False, the shape of the OLE container remains constant. The picture of the
OLE object is clipped to fit in the shape of the OLE container when deactivated. This
clipping does not affect the OLE object itself, however. The user can still access the entire
OLE object when it is activated.
Example
The following code resizes OLEContainer1 automatically when activated:
OLEContainer1.AutoSize := True;
AutoUnload property
Applies to
TReport component
Declaration
property AutoUnload: Boolean;
The AutoUnload property determines whether ReportSmith Runtime unloads from
memory when you have finished running a report.
If AutoUnload is True, ReportSmith Runtime unloads as soon as the report is finished
running.
If AutoUnload is False, ReportSmith Runtime remains in memory. For example, you can
create an application that includes a menu item that runs a report. After the report runs,
you want ReportSmith Runtime to stay in memory so the report can be quickly rerun
again. To remove ReportSmith Runtime from memory when AutoUnload is False, you
+
must then call the CloseApplication method. B
Example
The following code sets AutoUnload to False, so that Report1 can be run twice using two
different variables. After the second run, ReportSmith is unloaded by a call to
CloseApplication.
Report1.AutoUnload := False;
if Report1.SetVariable(‘FName’, ‘Linda’) then
Report1.Run;
if Report1.SetVariable(‘LName’, ‘King’) then
Report1.Run;
Report1.CloseApplication(False);
Back method
Applies to
TMediaPlayer component
Declaration
procedure Back;
The Back method steps backward a number of frames (determined by the value of the
Frames property) in the currently loaded medium. Back is called when the Back button
on the media player control is clicked at run time.
Upon completion, Back stores a numerical error code in the Error property and the
corresponding error message in the ErrorMessage property.
The Wait property determines whether control is returned to the application before the
Back method has been completed. The Notify property determines whether Back
generates an OnNotify event.
Example
The following example lets the user pick an .AVI video file using OpenDialog1 and
opens that file in MediaPlayer1. Then, the Back button can be used to step backward
through the .AVI clip. You could use this to hide MediaPlayer1 and design your own
user interface for the media player.
procedure TForm1.OpenClick(Sender: TObject);
begin
OpenDialog1.Filename := '*.*';
if OpenDialog1.Execute then
begin
MediaPlayer1.Filename := OpenDialog1.Filename;
MediaPlayer1.Open;
end;
end;
See also
Capabilities property, OnClick event, Rewind method, Step method
BackgroundColor property
Applies to
TTabSet component
Declaration
property BackgroundColor: TColor;
The BackgroundColor property determines the background color of the tab set control.
The background area of the tab set control is the area between the tabs and the border of
the control. For a list of possible color values, see the Color property.
Example
This code changes the background color of the tab set control:
TabSet1.BackgroundColor := clBackground;
See also
DitherBackground property
BatchMove method
Applies to
TTable component
Declaration
function BatchMove(ASource: TDataSet; AMode: TBatchMode): Longint;
The BatchMove method copies, appends, updates, or deletes records in the TTable.
ASource is a TTable linked to a database table containing the source records. AMode is the
copy mode; it can be any of the elements of TBatchMode: batAppend, batUpdate,
batAppendUpdate, batDelete, or batCopy.
BatchMove returns the number of records operated on.
Example
Table1.BatchMove(Table2, batAppend);
Declaration
property BeforeCancel: TDataSetNotifyEvent;
The BeforeCancel event is activated at the beginning of a call to the Cancel method. This
event is the first action taken by Cancel. If the dataset is not in Edit state or there are no
changes pending, then Cancel will not activate the BeforeCancel event.
By assigning a method to this property, you can take any special actions required by the
event. By raising an exception in this event handler, you can prevent the Cancel
operation from occurring.
See also
AfterCancel event
BeforeClose event
Applies to
TTable, TQuery, TStoredProc components
Declaration
property BeforeClose: TDataSetNotifyEvent;
The BeforeClose event is activated before the dataset is closed, either by calling the Close
method or by setting the Active property to False. This event is the first action taken by
Close.
By assigning a method to this property, you can take any special actions required by the
event. By raising an exception in this event handler, you can prevent the Close operation
from occurring.
See also
AfterClose event
BeforeDelete event
Applies to
TTable, TQuery, TStoredProc components
Declaration
property BeforeDelete: TDataSetNotifyEvent;
The BeforeDelete event is activated when the dataset begins a call to Delete. This event is
the first action taken by the Delete method.
By assigning a method to this property, you can take any special actions required by the
event. By raising an exception in this event handler, you can prevent the Delete
operation from occurring.
See also
AfterDelete event
BeforeEdit event
Applies to
TTable, TQuery, TStoredProc components
Declaration
property BeforeEdit: TDataSetNotifyEvent;
The BeforeEdit event is activated when the dataset begins a call to the Edit method. This
event is the first action taken by Edit.
By assigning a method to this property, you can take any special actions required by the
event. By raising an exception in this event handler, you can prevent the Edit operation
from occurring.
See also
AfterEdit event
BeforeInsert event
Applies to
TTable, TQuery, TStoredProc components
Declaration
property BeforeInsert: TDataSetNotifyEvent;
The BeforeInsert event is activated when the dataset begins a call to the Insert or Append
+
methods. This event is the first action taken by Insert or Append. B
By assigning a method to this property, you can take any special actions required by the
event. By raising an exception in this event handler, you can prevent the Insert operation
from occurring.
See also
AfterInsert event
BeforeOpen event
Applies to
TTable, TQuery, TStoredProc components
Declaration
property BeforeOpen: TDataSetNotifyEvent;
The BeforeOpen event is activated before the dataset is opened, either by calling the Open
method or by setting the Active property to True. This event is the first action taken by
the Open method. Typically, the BeforeOpen event handler opens any private lookup
tables used by other event handlers in the dataset.
By assigning a method to this property, you can take any special actions required by the
event. By raising an exception in this event handler, you can prevent the Open operation
from occurring.
See also
AfterOpen event
BeforePost event
Applies to
TTable, TQuery, TStoredProc components
Declaration
property BeforePost: TDataSetNotifyEvent;
The BeforePost event is activated at the beginning of a call to the Post method. This event
is the first action taken by the Post method, after it calls the UpdateRecord method to
reflect any changes made to the record by data controls. The BeforePost event can be
used to validate a record before it is posted. By raising an exception, a BeforePost event
handler can prevent the posting of an invalid record.
By assigning a method to this property, you can take any special actions required by the
event. By raising an exception in this event handler, you can prevent the Post operation
from occurring.
See also
AfterPost event
BeginDoc method
Applies to
TPrinter object
Declaration
procedure BeginDoc;
The BeginDoc method sends a print job to the printer. If the print job is sent successfully,
the application should call EndDoc to end the print job. The print job won’t actually start
printing until EndDoc is called.
To use the BeginDoc method, you must add the Printers unit to the uses clause of your
unit.
Example
This code prints a rectangle on the default printer:
begin
Printer.BeginDoc; { begin to send print job to printer }
Printer.Canvas.Rectangle(20,20,1000,1000); { draw rectangle on printer's canvas }
Printer.EndDoc; { EndDoc ends and starts printing print job }
end;
To use the BeginDoc method, you must add the Printers unit to the uses clause of your
unit.
See also
Abort method, Printer variable
BeginDrag method
Applies to
All controls
Declaration
procedure BeginDrag(Immediate: Boolean);
The BeginDrag method starts the dragging of a control. If the Immediate parameter is
+
True, the mouse pointer changes to the value of the DragCursor property and dragging
begins immediately. If Immediate is False, the mouse pointer doesn’t change to the value
B
of the DragCursor property and dragging doesn’t begin until the user moves the mouse
pointer a short distance (5 pixels). This allows the control to accept mouse clicks without
beginning a drag operation.
Your application needs to call the BeginDrag method to begin dragging only when the
DragMode property value for the control is dmManual.
Example
procedure TForm1.Button1Click(Sender: TObject);
begin
if Button1.DragMode = dmManual then
Button1.BeginDrag(True);
end;
See also
DragMode property, EndDrag method, OnDragDrop event, OnDragOver event,
OnEndDrag event
BeginUpdate method
Applies to
TStringList, TStrings objects; TOutline component
Declaration
procedure BeginUpdate;
The BeginUpdate method prevents the updating of the outline or string object until the
EndUpdate method is called. For string objects, BeginUpdate prevents the screen from
being repainted when new strings are added. For outlines, BeginUpdate prevents the
screen from being repainted and prevents outline items from being reindexed when
new items are added, deleted, or inserted. Outline items affected by the changes will
have invalid Index values until EndUpdate is called.
For example, the Lines property of a memo component is of type TStrings. If your
application calls the AddStrings method to add several strings at once to the Lines
property, AddStrings calls BeginUpdate before the strings are added. After the strings are
added, AddStrings calls EndUpdate and the screen repaints, displaying the new list of
strings.
Use BeginUpdate to prevent screen repaints and to speed processing time while you are
rebuilding your list.
Example
BeginUpdate and EndUpdate should always be used in conjunction with a try...finally
statement to ensure that EndUpdate is called if an exception occurs. A block that uses
BeginUpdate and EndUpdate typically looks like this:
ListBox1.Items.BeginUpdate;
try
ListBox1.Items.Clear;
ListBox1.Items.Add(...);
...
ListBox1.Items.Add(...);
finally
ListBox1.Items.EndUpdate; { Executed even in case of an exception }
end;
See also
EndUpdate method
BevelInner property
Applies to
TPanel component
Declaration
property BevelInner: TPanelBevel;
A panel component has two bevels, an outer bevel drawn next to the border of the
control, and an inner bevel drawn inside the outer bevel the number of pixels specified
in the BorderWidth property.
The BevelInner property determines the style of the inner bevel of a panel component.
These are the possible values:
Value Meaning
bvNone No inner bevel exists.
bvLowered The inner bevel is lowered.
bvRaised The inner bevel is raised.
Example
This example uses a panel component and a button named CreateStatusLine on a form.
The code moves the panel to the bottom of the form when the user clicks the button and
gives the panel the appearance of a status line by changing the value of the BevelInner,
BevelOuter, BevelWidth, and BorderWidth properties.
procedure TForm1.CreateStatusLineClick(Sender: TObject);
begin
with Panel1 do
begin
See also
BevelOuter property, BevelWidth property, BorderWidth property, TPanelBevel type
BevelOuter property
Applies to
TPanel component
Declaration
property BevelOuter: TPanelBevel;
A panel component has two bevels, an outer bevel drawn next to the border of the
control, and an inner bevel drawn inside the outer bevel. The width of the inner bevel is
specified in the BorderWidth property in pixels.
The BevelOuter property determines the style of the outer bevel of a panel component.
These are the possible values:
Value Meaning
bvNone No outer bevel exists.
bvLowered The outer bevel is lowered.
bvRaised The outer bevel is raised.
Example
This code creates a lowered frame 10 pixels wide around a panel component named
Panel1:
Panel1.BorderWidth := 10;
Panel1.BevelInner := bvRaised;
Panel1.BevelOuter := bvLowered;
See also
BevelInner property, BevelWidth property, BorderWidth property
BevelWidth property
Applies to
TPanel component
Declaration
property BevelWidth: TBevelWidth;
The BevelWidth property determines the width in pixels between the inner and the outer
bevels of a panel. The BevelInner property determines how the inner bevel appears, and
the BevelOuter property determines how the outer bevel appears. By changing these
properties, you change the appearance of the panel.
Example
This code alternately displays and hides the bevels of a panel when the user clicks the
Button1 button:
procedure TForm1.Button1Click(Sender: TObject);
begin
with Panel1 do
begin
BevelInner := bvLowered;
BevelOuter := bvRaised;
if BevelWidth = 0 then
BevelWidth := 2
else
BevelWidth := 0;
end;
end;
See also
BorderWidth property
Bitmap property
Applies to
TBrush, TPicture objects
For brushes
Declaration
property Bitmap: TBitmap;
Run-time only. The Bitmap property enables a brush to use a bitmap image for painting
with the ability to produce special painting effects such as patterns. The bitmap must be
8 pixels high and 8 pixels wide.
Example
The following code loads a bitmap from a file and assigns it to the Brush of the Canvas of
Form1:
Example
The following code copies the bitmap in Picture1 to the Glyph of BitBtn1.
BitBtn1.Glyph := Picture1.Bitmap;
See also
Graphic property
{$I+} lets you handle run-time errors using exceptions. For more information on
handling run-time library exceptions, see Handling RTL Exceptions in the Help system.
If you are using {$I–}, you must use IOResult to check for I/O errors.
Example
var
FromF, ToF: file;
NumRead, NumWritten: Word;
Buf: array[1..2048] of Char;
begin
if OpenDialog1.Execute then { Display Open dialog box }
begin
AssignFile(FromF, OpenDialog1.FileName);
Reset(FromF, 1); { Record size = 1 }
if SaveDialog1.Execute then { Display Save dialog box}
begin
AssignFile(ToF, SaveDialog1.FileName); { Open output file }
Rewrite(ToF, 1); { Record size = 1 }
Canvas.TextOut(10, 10, 'Copying ' + IntToStr(FileSize(FromF))
+ ' bytes...');
repeat
BlockRead(FromF, Buf, SizeOf(Buf), NumRead);
BlockWrite(ToF, Buf, NumRead, NumWritten);
until (NumRead = 0) or (NumWritten <> NumRead);
CloseFile(FromF);
CloseFile(ToF);
end;
end;
end;
See also
BlockWrite procedure
error occurs if Count * RecSize is greater than 65,535 (64K). You can use the exception
+
handler EInOutError to deal with this error. B
If the entire block is transferred, Result is equal to Count on return.
If Result is less than Count, the disk became full before the transfer was complete. In this
case, if the file’s record size is greater than 1, Result returns the number of complete
records written.
The current file position is advanced by Result records as an effect of the BlockWrite.
If Result isn’t specified, an I/O error occurs if the number written isn’t equal to Count.
You can use exception handler EInOutError to deal this error.
{$I+} lets you handle run-time errors using exceptions. For more information on
handling run-time library exceptions, see Handling RTL Exceptions in the Help system.
If you are using {$I–}, you must use IOResult to check for I/O errors.
Example
var
FromF, ToF: file;
NumRead, NumWritten: Word;
Buf: array[1..2048] of Char;
begin
if OpenDialog1.Execute then { Display Open dialog box }
begin
AssignFile(FromF, OpenDialog1.FileName);
Reset(FromF, 1); { Record size = 1 }
if SaveDialog1.Execute then { Display Save dialog box }
begin
AssignFile(ToF, SaveDialog1.FileName); { Open output file }
Rewrite(ToF, 1); { Record size = 1 }
Canvas.TextOut(10, 10, 'Copying ' + IntToStr(FileSize(FromF))
+ ' bytes...');
repeat
BlockRead(FromF, Buf, SizeOf(Buf), NumRead);
BlockWrite(ToF, Buf, NumRead, NumWritten);
until (NumRead = 0) or (NumWritten <> NumRead);
CloseFile(FromF);
CloseFile(ToF);
end;
end;
end;
See also
BlockRead procedure
BOF property
Applies to
TTable, TQuery, TStoredProc components
Declaration
property BOF: Boolean;
Run-time and read only. BOF is a Boolean property that indicates whether a dataset is
known to be at its first row. The BOF property returns a value of True only after:
• An application first opens a table
• A call to a table’s First method
• A call to a table’s Prior method fails
Example
Table1.Last;
while not Table1.BOF do
begin
{DoSomething}
Table1.Prior;
end;
See also
MoveBy method
Example
The following code calculates the BOLEMedium associated with CF_BITMAP and stores
it in the fmtMedium field of the first element of a BOLEFormat record array.
var
Fmts: array[0..2] of BOLEFormat;
begin
Fmts[0].fmtId := CF_BITMAP;
Fmts[0].fmtMedium := BOLEMediumCalc(CF_BITMAP);
Fmts[0].fmtIsLinkable := False;
StrPCopy (Fmts[0].fmtName, '%s');
StrPCopy (Fmts[0].fmtResultName, '%s');
end;
BorderColor property
Applies to
TShape component
Declaration
property BorderColor: TColor;
The BorderColor property is used to color the border of a shape component. For a
complete list of the values the BorderColor property can have, see the Color property.
Example
This example changes the border color of a shape component at run time:
Shape1.BorderColor := clBlack;
BorderIcons property
Applies to
TForm component
Declaration
property BorderIcons: TBorderIcons;
The BorderIcons property is a set whose values determine which icons appear on the title
bar of a form. These are the possible values that the BorderIcons set can contain:
Value Meaning
biSystemMenu The form has a Control menu (also known as a System menu)
biMinimize The form has a Minimize button
biMaximize The form has a Maximize button
Example
The following code removes a form’s Maximize button when the user clicks a button:
procedure TForm1.Button1Click(Sender: TObject);
BorderStyle property
Applies to
TDBEdit, TDBGrid, TDBImage, TDBListBox, TDBLookupCombo, TDBLookupList,
TDBMemo, TDrawGrid, TEdit, TForm, THeader, TListBox, TMaskEdit, TMemo,
TOLEContainer, TOutline, TPanel, TScrollBox, TStringGrid components
For forms
Declaration
property BorderStyle: TFormBorderStyle;
The BorderStyle property for forms specifies both the appearance and the behavior of the
form border. You normally set BorderStyle at design time, but you can also change it at
run time.
BorderStyle can have any of the following values:
Value Meaning
bsDialog Not resizeable; standard dialog box border
bsSingle Not resizeable; single-line border
bsNone Not resizeable; no visible border line, Minimize or Maximize
buttons, or Control menu
bsSizeable Standard resizeable border
Changing the border style of an MDI child form to bsDialog or bsNone has no effect.
Example
This example creates a form with a single-line border that the user can’t resize:
Form1.BorderStyle := bsSingle;
See also
BorderIcons property
For controls
Declaration
property BorderStyle: TBorderStyle;
The BorderStyle property of edit boxes, list boxes, memo controls, grid controls, outlines,
and scroll boxes determines whether these components have a border. These are the
possible values:
Value Meaning
bsNone No visible border
bsSingle Single-line border
If you set the AutoSize property of an edit box to True, the edit box resizes automatically
when the font size of the text changes. You must set the value of the BorderStyle property
to fsSingle, or else AutoSize has no effect.
Example
The following example puts a single-line border around the edit box, Edit1.
Edit1.BorderStyle := bsSingle;
See also
Ctl3D property
BorderWidth property
Applies to
TPanel component
Declaration
property BorderWidth: TBorderWidth;
The BorderWidth property determines the width in pixels of the border around a panel.
The default value is 0, which means no border.
Example
This example uses a panel component and a button named CreateStatusLine on a form.
The code moves the panel to the bottom of the form when the user clicks the button, and
gives the panel the appearance of a status line by changing the value of the BevelInner,
BevelOuter, BevelWidth, and BorderWidth properties:
procedure TForm1.CreateStatusLineClick(Sender: TObject);
begin
with Panel1 do
Align := alBottom;
See also
BevelInner property, BevelOuter property, BevelWidth property
Example
This example returns a TRect record that defines a rectangle that is 100 pixels long on
each side with the top left corner at coordinate 10, 10.
var
R: TRect;
begin
R := Bounds(10, 10, 100, 100);
end;
See also
BoundsRect property
BoundsRect property
Applies to
All controls
Declaration
property BoundsRect: TRect;
The BoundsRect property returns the bounding rectangle of the control, expressed in the
coordinate system of the parent control. The statement
R := Control.BoundsRect;
corresponds to
R.Left := Control.Left;
R.Top := Control.Top;
R.Right := Control.Left + Control.Width;
R.Bottom := Control.Top + Control.Height;
Example
This code resizes a button control to twice as wide and half as high:
procedure TForm1.Button1Click(Sender: TObject);
var
MyRect: TRect;
begin
MyRect := Button2.BoundsRect;
MyRect.Right := MyRect.Left + 2 * (MyRect.Right - MyRect.Left);
MyRect.Bottom := MyRect.Top + (MyRect.Bottom - MyRect.Top) div 2;
Button2.BoundsRect := MyRect;
end;
See also
Bounds function
Example
uses WinCRT;
var
S: string;
begin
while True do
begin
ReadLn(S);
if S = '' then Break;
WriteLn(S);
end;
end;
See also
Continue procedure, Exit procedure, Halt procedure
Declaration
property Break: TMenuBreak;
The Break property lets you break a long menu into columns. These are the possible
values:
Value Meaning
mbNone No menu breaking occurs.
mbBarBreak The menu breaks into another column with the menu item appearing at the top of the
new column. A bar separates the new and the old columns.
mbBreak The menu breaks into another column with the menu item appearing at the top of the
new column. Only space separates the new and the old columns.
Example
This example uses a button and a main menu component with several subitems on it,
including one labeled Save As, so that Delphi automatically names that menu item
SaveAs1. When the user clicks the button on the form, the menu breaks so Save As
appears in a second column with a bar between the two columns. The change to the
menu is visible when the menu displays.
procedure TForm1.Button1Click(Sender: TObject);
begin
SaveAs1.Break := mbBarBreak;
end;
See also
Checked property, Enabled property
BringToFront method
Applies to
All controls; TForm component
Declaration
procedure BringToFront;
The BringToFront method puts the component or form in front of all other components
or forms within its parent component or form. BringToFront is especially useful for
making certain that a form is visible. You can also use it to reorder overlapping
components within a form.
The order in which controls stack on top of each order (also called the Z order) depends
on whether the controls are windowed or non-windowed controls. For example, if you
put a label and an image on a form so that one is on top of the other, the one you placed
first on the form is the one on the bottom. Because both the label and the image are non-
windowed controls, they “stack” as you would expect them to. Suppose that the label is
on the bottom. If you call the BringToFront method for the label, the label then appears
on top of the image.
The stacking order of windowed controls is the same. For example, if you put a memo
on a form, then put a check box on top of it, the check box remains on top. If you call
BringToFront for the memo, the memo appears on top.
The stacking order of windowed and non-windowed controls cannot be mingled. For
example, if you put a memo, a windowed control, on a form, and then put a label, a non-
windowed control, on top of it, the label disappears behind the memo. Windowed
controls always stack on top of non-windowed controls. In this example, if you call the
BringToFront method of the label, it remains behind the memo.
Example
The following code uses two forms. Form1 has a button on it. The second form is used as
a tool palette. This code makes the palette form visible, and ensures it is the top form by
bringing it to the front.
To run this example, you must put Unit2 in the uses clause of your unit.
procedure TForm1.ShowPaletteButtonClick(Sender: TObject);
begin
if Form2.Visible = False then Form2.Visible := True;
Form2.BringToFront;
end;
See also
SendToBack method
Brush property
Applies to
All controls; TCanvas object; TForm, TShape components
Declaration
property Brush: TBrush;
A canvas or shape object’s Brush property determines what kind of color and pattern the
canvas uses for filling graphical shapes and backgrounds. Controls also specify an
additional brush in their Brush properties, which they use for painting their
backgrounds.
See also
BrushCopy method, Canvas property, Font property, Pen property, TCanvas object
BrushCopy method
Applies to
TCanvas object
Declaration
procedure BrushCopy(const Dest: TRect; Bitmap: TBitmap; const Source: TRect; Color: TColor);
The BrushCopy method copies a portion of a bitmap onto a portion of a canvas, replacing
one of the colors of the bitmap with the brush of the destination canvas. Dest specifies
the rectangular portion of the destination canvas to copy to. Bitmap specifies the graphic
to copy from. Source specifies the rectangular area of the bitmap to copy. Color specifies
the color in Bitmap to replace with the brush of the canvas (specified in the Brush
property).
You could use BrushCopy to make the copied image partially transparent, for example.
To do this, you would specify the color of the surface being copied to (clBackground for
example) as the Color of the Brush property of the destination canvas, then call
BrushCopy.
Example
The following code illustrates the differences between CopyRect and BrushCopy. The
bitmap graphic ‘TARTAN.BMP’ is loaded into Bitmap and displayed on the Canvas of
Form1. BrushCopy replaces the color black in the graphic with the brush of the canvas,
while CopyRect leaves the colors intact.
var
Bitmap: TBitmap;
MyRect, MyOther: TRect;
begin
MyRect.Top := 10;
MyRect.Left := 10;
MyRect.Bottom := 100;
MyRect.Right := 100;
MyOther.Top := 111; {110}
MyOther.Left := 10;
MyOther.Bottom := 201; {210}
MyOther.Right := 100;
Bitmap := TBitmap.Create;
Bitmap.LoadFromFile('c:\windows\tartan.bmp');
Form1.Canvas.BrushCopy(MyRect,Bitmap, MyRect, clBlack);
Form1.Canvas.CopyRect(MyOther,Bitmap.Canvas,MyRect);
Bitmap.Free;
end;
See also
Brush property, CopyRect method
BtnClick method
Applies to
TDBNavigator component
Declaration
procedure BtnClick(Index: TNavigateBtn);
The BtnClick method simulates a button click on the database navigator, invoking the
action of the button. Specify which button BtnClick should operate on as the value of the
Index parameter.
Example
This line of code simulates the clicking of the Next button on a database navigator
control, which makes the next record in the dataset the current record:
DBNavigator1.BtnClick(nbNext);
Buttons property
Applies to
TDBRadioGroup, TRadioGroup components
Example
The following code disables the first button in DBRadioGroup1.
TRadioButton(DBRadioGroup1.Buttons.First).Enabled := False;
Calculated property
Applies to
TBCDField, TBlobField, TBooleanField, TBytesField, TCurrencyField, TDateField,
TDateTimeField, TFloatField, TGraphicField, TIntegerField, TMemoField, TSmallintField,
TStringField, TTimeField, TVarBytesField, TWordField components
Declaration
property Calculated: Boolean;
Calculated is True if the value of the field is calculated by the OnCalcFields event handler.
Calculated fields can be created with the Fields Editor, but are not stored in or retrieved
from the physical tables underlying a dataset. Instead they are calculated for each record
in the table by the dataset’s OnCalcFields event handler, which typically uses expressions
involving values from other fields in the record to generate a value for each calculated
field. For example, a table might have non-calculated fields for Quantity and UnitPrice,
and a calculated field for ExtendedPrice, which would be calculated by multiplying the
values of the Quantity and UnitPrice fields. Calculated fields are also useful for
performing lookups in other tables. For example, a part number can be used to retrieve a
part description for display in an invoice line item.
Cancel method
Applies to
TTable, TQuery, TStoredProc components
Declaration
procedure Cancel;
The Cancel method returns the dataset to Browse state and discards any changes to the
current record.
See also
Append method, Insert method, Post method
Cancel property
Applies to
TBitBtn, TButton components
Declaration
property Cancel: Boolean;
The Cancel property indicates whether a button or a bitmap button is a Cancel button. If
Cancel is True, any time the user presses Esc, the OnClick event handler for the button
executes. Although your application can have more than one button designated as a
Cancel button, the form calls the OnClick event handler only for the first button in the
tab order that is visible.
Example
The following code designates a button called Button1 as a Cancel button:
Button1.Cancel := True;
See also
Default property, OnClick event
CancelRange method
Applies to
TTable component
Declaration
procedure CancelRange;
The CancelRange method removes any range limitations for the TTable which were
previously established by calling the ApplyRange or SetRange methods.
Example
Table1.CancelRange;
CanFocus method
Applies to
All controls
Example
This example uses a group box, a label, and a button on a form. The group box contains
a check box. When the application runs, the group box is disabled (Enabled is set to
False). Because the group box is the parent of the check box, the user can never tab to the
check box. When the user clicks the button, the caption of the label reports that the check
box can not receive the input focus:
procedure TForm1.FormCreate(Sender: TObject);
begin
GroupBox1.Enabled := True;
end;
procedure TForm1.Button1Click(Sender: TObject);
begin
if CheckBox1.CanFocus then
Label1.Caption := 'The check box can focus'
else
Label1.Caption := 'The check box cannot focus';
end;
See also
Parent property
CanModify property
Applies to
TBCDField, TBlobField, TBooleanField, TBytesField, TCurrencyField, TDateField,
TDateTimeField, TFloatField, TGraphicField, TIntegerField, TMemoField, TSmallintField,
TStoredProc, TStringField, TQuery, TTable, TTimeField, TVarBytesField, TWordField
components
put into Edit or Insert state. When CanModify is True, the dataset can enter Edit or Insert
state.
Even if CanModify is True, it is not a guarantee that a user will be able to insert or update
records in a table. Other factors may come in to play, for example, SQL access privileges.
TTable has a ReadOnly property that requests write privileges when set to False. When
ReadOnly is True, CanModify will automatically be set to False. When ReadOnly is False,
CanModify will be True if the database allows read and write privileges for the dataset
and the underlying table.
Example
if Table1.CanModify then
{ Do this only if the dataset can be modified }
Table1.CustNo := 1234;
See also
Active property
See also
DataSet property
Canvas property
Applies to
TBitmap, TComboBox, TDBComboBox, TDBGrid, TDBListBox, TDirectoryListBox,
TDrawGrid, TFileListBox, TForm, TImage, TListBox, TOutline, TPaintBox, TPrinter,
TStringGrid components
Run-time only. The Canvas property gives you access to a drawing surface that you can
+
use when implementing a handler for the OnPaint event of a form, an image, or a paint
box.
+
The Canvas property of an image or a form is read only. C
Example
The following code sets the Color of the Pen of the Canvas of Bitmap1 to clBlue.
Bitmap1.Canvas.Pen.Color := clBlue;
See also
Search for Graphics in online Help and choose the topic Drawing Graphics at Run Time
Example
The following code draws a graphic stored in the Objects property of the Items list of
ListBox1. This code should be attached to the OnDrawItem event handler of ListBox1, and
the Style property of ListBox1 should be lbOwnerDrawFixed.
procedure TForm1.ListBox1DrawItem(Control: TWinControl; Index: Integer;
Rect: TRect; State: TOwnerDrawState);
var
SourceRect: TRect;
begin
SourceRect.Top := 0;
SourceRect.Left := 0;
SourceRect.Bottom := TBitmap(ListBox1.Items.Objects[Index]).Height;
SourceRect.Right := TBitmap(ListBox1.Items.Objects[Index]).Width;
ListBox1.Canvas.CopyRect(Rect, TBitmap(ListBox1.Items.Objects[Index]).Canvas,
SourceRect);
end;
The following code draws a graphic stored in the Data property of the Items list of
Outline1. This code should be attached to the OnDrawItem event handler of Outline1,
and the Style property of Outline1 should be otOwnerDraw.
procedure TForm1.Outline1DrawItem(Control: TWinControl; Index: Integer;
Rect: TRect; State: TOwnerDrawState);
var
SourceRect: TRect;
begin
SourceRect.Top := 0;
SourceRect.Left := 0;
SourceRect.Bottom := TBitmap(Outline1.Items[Index].Data).Height;
SourceRect.Right := TBitmap(Outline1.Items[Index].Data).Width;
Outline1.Canvas.CopyRect(Rect, TBitmap(Outline1.Items[Index].Data).Canvas,
SourceRect);
end;
See also
ItemHeight property, OnDrawCell event, OnDrawDataCell event, OnDrawItem event,
OnPaint event
For grids
Declaration
property Canvas: TCanvas;
Run-time and read only. The Canvas property gives you access to a drawing surface that
you can use when implementing a handler for the OnDrawCell or OnDrawDataCell event
of a grid control.
Example
The following code prints the text ‘Hello, world!’:
Printer.BeginDoc;
Printer.Canvas.TextOut(0, 0, 'Hello, world');
Pritner.EndDoc;
See also
Brush property, Font property, Pen property, TextOut method
See also
Draw method
Capabilities property
Applies to
TMediaPlayer component
Declaration
property Capabilities: TMPDevCapsSet;
Run-time and read only. The Capabilities property determines the capabilities of the
open multimedia device.
The various capabilities specified in Capabilities are determined when the device is
opened with the Open method. The following table lists the capabilities a device can
have:
Value Capability
mpCanEject Can eject media
mpCanPlay Can play media
mpCanRecord Can record media
mpCanStep Can step forward or backward within media
mpUsesWindows Uses a window for displaying output
Note Currently, there is no way to check whether a device can step forward or backward.
Capabilities includes mpCanStep only if the device type (specified in the DeviceType
property) is Animation, AVI Video, Digital Video, Overlay, or VCR.
Example
The following code determines whether the device opened by the media player control
MediaPlayer1 uses a window to display output. If so, the output displays in a form
named Form2:
if mpUsesWindows in MediaPlayer1.Capabilities then
MediaPlayer1.Display := Form2;
See also
Back method, Display property, Eject method, Play method, StartRecording method, Step
method
Capacity property
Applies to
TList object
Declaration
property Capacity: Integer;
Run time only. The Capacity property contains the allocated size of the array of pointers
maintained by a TList object. This is different from the Count property, which contains
the number of entries that are actually in use. The value of the Capacity property is
always greater than or equal to the value of the Count property.
When setting the Capacity property, an EListError exception occurs if the specified value
is less than the Count property or greater than 16380 (the maximum number of elements
a list object can contain). Also, an EOutOfMemory exception occurs if there is not enough
memory to expand the list to its new size.
When an element is added to a list whose Capacity and Count are equal (indicating that
all allocated entries are in use), the Capacity is automatically increased by 16 elements. In
situations where you are going to be adding a known number of elements to a list, you
can reduce memory reallocations by first increasing the list's capacity. For example,
List.Clear;
List.Capacity := Count;
for I := 1 to Count do List.Add(...);
The assignment to Capacity before the for loop ensures that each of the following Add
operations doesn’t cause the list to be reallocated, which in turn means that the Add
operations are guaranteed to never raise an exception.
Example
The following code sets the Capacity of List1 to 5.
List1.Capacity := 5;
See also
Count property, Expand method, Items property, Pack method
Caption property
Applies to
TBitBtn, TButton, TCheckBox, TDBCheckBox, TDBRadioGroup, TForm, TGroupBox, TLabel,
TMenuItem, TPanel, TRadioButton, TSpeedButton components
Example
The following code creates a caption that says “Hello, World!” on a form called MyForm:
MyForm.Caption := ‘Hello, World!’;
See also
BorderStyle property
Example
This code changes the caption of a group box:
procedure TForm1.Button1Click(Sender: TObject);
begin
GroupBox1.Caption := ’Fancy options’;
end;
See also
FocusControl property, ShowAccelChar property, Text property
Cascade method
Applies to
TForm component
Declaration
procedure Cascade;
The Cascade method rearranges the child forms in your application so they overlap. The
top of each form remains visible so that you can easily select one of the forms. The
Cascade method applies only to MDI parent forms (with a FormStyle property value of
fsMDIForm).
Example
This code arranges all MDI children of the current MDI parent form in a cascade pattern
when the user chooses the Cascade menu command:
procedure TForm1.Cascade1Click(Sender: TObject);
begin
Cascade;
end;
See also
ArrangeIcons method, Next method, Previous method, Tile method
CellRect method
Applies to
TDrawGrid, TStringGrid components
Declaration
function CellRect(ACol, ARow: Longint): TRect;
The CellRect method creates a rectangle of type TRect for the cell defined by the column
ACol and the row ARow. If the cell indicated by ACol and ARow is not visible, CellRect
returns an empty rectangle.
Example
This example uses a string grid, four labels, and a button on a form. When the user clicks
the button, the coordinates of the cell in the second column and first row appear in the
label captions:
procedure TForm1.Button1Click(Sender: TObject);
var
Rectangle: TRect;
begin
Rectangle := StringGrid1.CellRect(3, 2);
Cells property
Applies to
TStringGrid component
Declaration
property Cells[ACol, ARow: Integer]: string;
Run-time only. The Cells property is an array of strings, one string for each cell in the
grid. Use the Cells property to access a string within a particular cell. ACol is the column
coordinate of the cell, and ARow is the row coordinate of the cell. The first row is row
zero, and the first column is column zero.
The ColCount and RowCount property values define the size of the array of strings.
Example
This code fills each cell of a grid with the same string.
procedure TForm1.Button1Click(Sender: TObject);
var
I, J: Integer;
begin
with StringGrid1 do
for I := 0 to ColCount - 1 do
for J:= 0 to RowCount - 1 do
Cells[I,J] := 'Delphi';
end;
See also
Cols property, Objects property, Rows property
Center property
Applies to
TDBImage, TImage components
Declaration
property Center: Boolean;
The Center property determines whether an image is centered in the image control. If
Center is True, the image is centered. If Center is False, the image aligns with the top left
corner of the control. The default value is True.
Example
The following code centers the image in Image1 when the user checks CheckBox1:
procedure TForm1.CheckBox1Click(Sender: TObject);
begin
Image1.Center := CheckBox1.Checked;
end;
See also
AutoSize property, Stretch property
ChangedCount property
Applies to
TBatchMove component
Declaration
property ChangedCount: Longint;
Run-time and read only. ChangedCount is the number of records added to the table
specified by ChangedTableName. If ChangedTableName is not specified, the count is still
valid.
Example
with BatchMove1 do
begin
Execute;
if ChangedCount <> Source.RecordCount then { something went wrong };
end;
See also
ChangedTableName property
ChangedTableName property
Applies to
TBatchMove component
Example
BatchMove1.ChangedTableName := ‘oldrecs.db’;
Example
The following code generates the name of an .INI file based on the name of the program:
function INIFileName: string;
begin
Result := ChangeFileExt(ParamStr(0), '.INI');
end;
ChangeLevelBy method
Applies to
TOutlineNode object
Declaration
procedure ChangeLevelBy(Value: TChangeRange);
The ChangeLevelBy method changes the level of an outline item. Specify a Value
parameter value of -1 to move up (toward the root) one level. Specify a Value parameter
value of 1 to move down (away from the root) one level.
When moving up one level, an item becomes the next sibling of its former parent. When
moving down one level, an item becomes the last child of its former prior sibling.
Therefore, you can not change the level of the first item in the outline, as it has no parent
or prior sibling. Also, you can not move items that are already on the first level up one
level.
ChangeLevelBy modifies the value of the Level property to reflect the new level. You can
only move an item up or down one level at a time.
Example
Attach the following code to the OnClick event handlers of two buttons to allow the user
to move the selected outline item up or down. The code for UpBtn checks to see if the
selected item is not already on the first level before moving it up. The code for DownBtn
checks to see if the selected item has a prior sibling before moving it down.
procedure TForm1.UpBtnClick(Sender: TObject);
begin
with Outline1[Outline1.SelectedItem] do
if Level > 1 then ChangeLevelBy(-1);
end;
See also
Level property, MoveTo method
CharCase property
Applies to
TDBEdit, TEdit, TMaskEdit components
Declaration
property CharCase: TEditCharCase;
The CharCase property determines the case of the Text property of the edit box. These are
the possible values:
Value Meaning
ecLowerCase The text of the edit box displays in lowercase
ecNormal The text of the edit box displays in mixed case
ecUpperCase The text of the edit box displays in uppercase
If the user tries to enter a different case than the current value of CharCase, the characters
the user enters appear in the case specified by CharCase. For example, if the value of
CharCase is ecLowerCase, only lowercase characters appear in the edit box, even if the
user tries to enter uppercase characters.
Example
This example uses an edit box and group box containing three radio buttons. When the
user selects the first radio button, the text in the edit box becomes lowercase, and any
text the user types in the edit box also appears in lowercase. When the user selects the
second radio button, the text in the edit box becomes uppercase, and any text the user
+
types in the edit box also appears in uppercase. When the user selects the third radio
button, the text in the edit box remains unchanged, but the user can type using either
+
upper- or lowercase characters:
procedure TForm1.RadioButton1Click(Sender: TObject);
C
begin
Edit1.CharCase := ecLowerCase;
end;
procedure TForm1.RadioButton2Click(Sender: TObject);
begin
Edit1.CharCase := ecUpperCase;
end;
procedure TForm1.RadioButton3Click(Sender: TObject);
begin
Edit1.CharCase := ecNormal;
end;
Example
begin
{$I–}
{ Change to directory specified in Edit1 }
ChDir(Edit1.Text);
if IOResult <> 0 then
MessageDlg('Cannot find directory', mtWarning, [mbOk], 0);
end;
See also
GetDir procedure, MkDir procedure, RmDir procedure
Check procedure DB
Declaration
procedure Check(Status: Integer);
The Check procedure tests Status for a nonzero value and calls DbiError passing Status.
CheckBrowseMode method
Applies to
TTable, TQuery, TStoredProc components
Declaration
procedure CheckBrowseMode;
The CheckBrowseMode method verifies that the dataset is open and has no pending
changes. If the dataset’s State property is dsEdit, dsInsert or dsSetKey, the Post method is
called to post any pending changes. If the dataset is closed, an EDataBaseError exception
will be raised.
Example
This example fills in a radio button at run time:
RadioButton1.Checked := True;
This example uses a main menu component that contains a menu item named
SnapToGrid1 on a form. When the user chooses the Snap To Grid command, a check
mark appears next to the command. When the user chooses the Snap To Grid command
again, the check marks disappears:
procedure TForm1.SnapToGrid1Click(Sender: TObject);
begin
SnapToGrid1.Checked := not SnapToGrid1.Checked;
end;
See also
AllowGrayed property, State property
The CheckEOF typed constant controls the end-of-file character checking in the CRT
window.
When CheckEOF is True, an end-of-file marker is generated when the user presses Ctrl+Z
while reading from a file assigned to the CRT window.
When CheckEOF is False, pressing Ctrl+Z has no effect.
CheckEOF is False by default.
Chord method
Applies to
TCanvas object
Declaration
procedure Chord(X1, Y1, X2, Y2, X3, Y3, X4, Y4: Integer);
The Chord method draws a line on the canvas connecting two points on the ellipse
bounded by the specified rectangle. The screen pixel coordinates (X1, Y1) and (X2, Y2)
define the enclosing rectangle for the chord. (X3,Y3) is the starting point for the line, and
(X4, Y4) is the ending point.
Example
This code draws a chord on the top of an ellipse bounded by the current window:
var
R: TRect;
begin
R := GetClientRect; {Gets the rectangular coordinates of the current window}
Canvas.Chord(R.Left, R.Top, R.Right, R.Bottom, R.Right, R.Top, R.Left, R.Top);
end;
See also
Arc method, Draw method, Ellipse method, Pie method
Example
begin
Canvas.TextOut(10, 10, Chr(65)); { The letter ‘A’}
Declaration
class function ClassName: string;
The ClassName function returns the name of an object or a class. For example,
TButton.ClassName returns the string ‘TButton’.
The name returned by ClassName is the name of the actual class of the object, as opposed
to the object’s declared class. For example, the following code assigns ’TButton’ to S, not
’TObject’:
var
MyObject: TObject;
S: string;
begin
MyObject := TButton.Create(Application);
S := MyObject.ClassName;
...
MyObject.Free;
end;
Example
This example uses a button, a label, a list box, a check box, and an edit box on a form.
When the user clicks one of the controls, the name of the control’s class appears in the
edit box.
procedure FindClassName(AControl:TObject);
begin
Form1.Edit1.Text := AControl.ClassName;
end;
procedure TForm1.Button1Click(Sender: TObject);
begin
FindClassName(Button1);
end;
procedure TForm1.Label1Click(Sender: TObject);
begin
FindClassName(Label1);
end;
procedure TForm1.CheckBox1Click(Sender: TObject);
begin
FindClassName(CheckBox1);
end;
procedure TForm1.ListBox1Click(Sender: TObject);
begin
FindClassName(ListBox1);
end;
See also
ClassParent method, ClassType method
ClassParent method
Applies to
All objects and components
Declaration
class function ClassParent: TClass;
The ClassParent method returns the parent class of an object or a class. The returned
value is the immediate ancestor of the object or class. For example, TScrollBar.
ClassParent returns TWinControl as TScrollBar is derived from TWinControl.
Note that TObject.ClassParent returns nil because TObject has no parent.
Example
This code example uses a button and a list box on a form. When the user clicks the
button, the name of the button’s class and the names of its parent classes are added to
the list box.
procedure TForm1.Button1Click(Sender: TObject);
var
ClassRef: TClass;
begin
ListBox1.Clear;
ClassRef := Sender.ClassType;
while ClassRef <> nil do
begin
ListBox1.Items.Add(ClassRef.ClassName);
ClassRef := ClassRef.ClassParent;
end;
end;
The list box contains the following strings after clicking the button:
TButton
TButtonControl
TWinControl
TControl
ClassType method
Applies to
All objects and components
Declaration
function ClassType: TClass;
The ClassType function returns the class of an object.
Example
This example uses a button and a label on a form. When the user clicks the button, the
type of the button component (TButton) appears in the caption of the label.
procedure TForm1.Button1Click(Sender: TObject);
var
ButtonClassType: TClass;
begin
ButtonClassType := Button1.ClassType;
Label1.Caption := ButtonClassType.ClassName;
end;
See also
ClassName method, ClassParent method
Clear method
Applies to
TClipboard, TFieldDefs, TIndexDefs, TList, TParam, TParams, TStringList, TStrings objects;
TBCDField, TBlobField, TBooleanField, TBytesField, TComboBox, TDBComboBox,
TCurrencyField, TDateField, TDateTimeField, TDBEdit, TDBListBox, TDBMemo,
TDirectoryListBox, TDriveComboBox, TEdit, TFileListBox, TFilterComboBox, TFloatField,
TGraphicField, TIndexDefs, TIntegerField, TListBox, TMaskEdit, TMemo, TMemoField,
TOutline, TSmallintField, TStringField, TTimeField, TVarBytesField, TWordField
components
Example
Params1.Clear;
Example
{ Clear the CustNo parameter for Query 1 }
Query1.ParamByName(‘CustNo’).Clear;
For fields
Declaration
procedure Clear;
Clear sets the value of the field to NULL.
Example
The following code removes the text from an edit box control called NameField:
NameField.Clear;
This example uses a list box and a button on a form. When the form is created, strings
are added to the list box. When the user clicks the button, all the strings contained in the
Items property, a TStrings object, are cleared.
procedure TForm1.FormCreate(Sender: TObject);
begin
ListBox1.Items.Add('One');
ListBox1.Items.Add('Two');
ListBox1.Items.Add('Three');
end;
procedure TForm1.Button1Click(Sender: TObject);
begin
ListBox1.Items.Clear;
end;
See also
CopyToClipboard method, CutToClipboard method, Items property, Pack method,
PasteFromClipboard method, Text property, Strings property
ClearFields method
Applies to
TTable, TQuery, TStoredProc components
Declaration
procedure ClearFields;
The ClearFields method clears all fields of the current record to their default values
(normally NULL.) The dataset must be in Edit state or an EDatabaseError exception will
be raised.
See also
Edit method, State property, TField component
Example
The following code clears Form1 of object formats:
ClearFormOLEDropFormats(Form1);
See also
SetFormOLEDropFormats procedure, TOLEDropNotify object
ClearSelection method
Applies to
TDBEdit, TDBMemo, TEdit, TMaskEdit, TMemo components
Declaration
procedure ClearSelection;
The ClearSelection method deletes text selected in an edit box or memo control. If no text
is selected in the control when ClearSelection is called, nothing happens.
Example
This code uses a memo control named MyMemo and a button on a form. When the user
clicks the button, the text the user selected in the memo control is deleted.
procedure TForm1.Button1Click(Sender: TObject);
begin
MyMemo.ClearSelection;
end;
See also
Clear method, CopyToClipboard method, CutToClipboard method, PasteFromClipboard
method
Example
This example uses a main menu component and a button named Print. The main menu
component has a Print1 menu item on it. When the user clicks the button, the code
attached to the OnClick event of the Print1 menu item runs.
procedure TForm1.PrintClick(Sender: TObject);
begin
Print1.Click;
end;
See also
OnClick event
Example
The following code simulates a click on the Next button of DBNavigator1.
DBNavigator1.Click(nbNext);
ClientHandle property
Applies to
TForm component
Declaration
property ClientHandle: HWND;
Read only. The ClientHandle property value is the handle to the internal MDI (Multiple
Document Interface) client window. The property value is meaningful only if the form
is an MDI parent form with its FormStyle property set to fsMDIForm.
ClientHeight property
Applies to
All controls; TForm component
Declaration
property ClientHeight: Integer;
The ClientHeight property is the height of the control’s client area in pixels. For most
controls, ClientHeight is exactly the same as Height. For forms, however, ClientHeight
represents the height of the usable area inside the form’s frame.
ClientHeight is a run-time only property for all controls except forms.
Example
This example reduces the height of the form’s client area by half when the user clicks the
button on the form:
procedure TForm1.Button1Click(Sender: TObject);
begin
Form1.ClientHeight := Form1.ClientHeight div 2;
end;
Note that only the client area is halved, not the entire form.
See also
ClientWidth property, Height property
ClientOrigin property
Applies to
All controls; TForm component
Declaration
property ClientOrigin: TPoint;
Run-time and read only. The ClientOrigin property is used to determine the screen
coordinates (in pixels) of the top left corner of a control or form client area. ClientOrigin
returns X and Y coordinates in a record of type Point.
See also
ClientRect property
ClientRect property
Applies to
All controls; TForm component
Declaration
property ClientRect: TRect;
Run-time and read only. The ClientRect property is used to determine the size (in pixels)
of a control or form client area. ClientRect returns the Top, Bottom, Left, and Right
coordinates in one record of type TRect.
Example
The following code uses ClientRect to find and draw a line from the top left to the bottom
right of the current form:
with ClientRect do
begin
Canvas.MoveTo(Left,Top);
Canvas.LineTo(Right, Bottom);
end;
See also
ClientOrigin property
ClientToScreen method
Applies to
All controls
Declaration
function ClientToScreen(Point: TPoint): TPoint;
The ClientToScreen method translates the given point from client area coordinates to
global screen coordinates. In client area coordinates (0, 0) corresponds to the upper left
corner of the control’s client area. In screen coordinates (0, 0) corresponds to the upper
left corner of the screen.
Using the ClientToScreen and ScreenToClient methods you can convert from one control’s
coordinate system to another control’s coordinate system. For example,
P := TargetControl.ScreenToClient(SourceControl.ClientToScreen(P));
which converts P from coordinates in SourceControl to coordinates in TargetControl.
Example
This example uses two edit boxes on a form. When the user clicks a point on the form,
the X screen coordinate appears in Edit1, and the Y screen coordinate appears in Edit2.
procedure TForm1.FormMouseDown(Sender: TObject; Button: TMouseButton;
Shift: TShiftState; X, Y: Integer);
var
P, Q : TPoint;
begin
P.X := X; { P is the TPoint record for the form}
P.Y := Y;
Q := ClientToScreen(P); { Q is the TPoint for the screen }
Edit1.Text := IntToStr(Q.X) + ' is the X screen coordinate';
Edit2.Text := IntToStr(Q.Y) + ' is the Y screen coordinate';
end;
See also
ScreenToClient method
ClientWidth property
Applies to
All controls
Declaration
property ClientWidth: Integer;
The ClientWidth property is the horizontal size of the control’s client area in pixels. For
most controls, ClientWidth is exactly the same as Width. For forms, however, ClientWidth
represents the width of the usable area inside the form’s frame.
ClientWidth is a run-time only property for all components except forms.
Example
This example uses a button on a form. Each time the user clicks the button, the button
grows 10 pixels wider.
ClipRect property
Applies to
TCanvas object
Declaration
property ClipRect: TRect;
Read only. The ClipRect property specifies a bounding clipping rectangle. The rectangle
specified by ClipRect defines the outer boundaries of the drawing area of the canvas.
Any drawing that occurs at coordinates outside the ClipRect are clipped and don’t
appear onscreen. For example, the ClipRect of the canvas of a form is the same size as the
client area of the form.
See also
ClientRect property
Close method
Applies to
TClipboard object; TDataBase, TForm, TMediaPlayer, TQuery, TStoredProc, TTable
components
For forms
Declaration
procedure Close;
The Close method closes a form. Calling the Close method on a form corresponds to the
user selecting the Close menu item on the form’s System menu. The Close method first
calls the CloseQuery method to determine if the form can close. If CloseQuery returns
False, the close operation is aborted. Otherwise, if CloseQuery returns True, the code
attached to the OnClose event is executed. The CloseAction parameter of the OnClose
event controls how the form is actually closed.
Example
The following method closes a form when a button called Done is clicked:
procedure TForm1.DoneButtonClick(Sender: TObject);
begin
Close;
end;
See also
Hide method, Open method
Example
The following code closes the Clipboard:
Clipboard.Close;
See also
Clipboard variable
See also
Open method
For databases
Declaration
procedure Close;
The Close method closes the TDatabase component and all the dataset components
linked to it. This is the same as setting the Connected property to False.
Example
Database1.Close;
See also
CloseDatasets method
The Close procedure terminates the association between the file variable and an external
disk file.
F is a file variable of any file type opened using Reset, Rewrite, or Append. The external
file associated with F is completely updated and then closed, freeing the file handle for
reuse.
{$I+} lets you handle run-time errors using exceptions. For more information on
handling run-time library exceptions, see Handling RTL Exceptions in the Help system.
If you are using {$I–}, you must use IOResult to check for I/O errors.
Example
var
F: TextFile;
begin
if OpenDialog1.Execute then { Bring up open file dialog }
begin
AssignFile(F, OpenDialog1.FileName);
{ File selected in dialog }
Reset(F);
Edit1.Text := IntToStr(FileSize(F);
{ Put file size string in a TEdit control }
CloseFile(F); { Close file }
end;
end;
See also
Append procedure, AssignFile procedure, Reset procedure, Rewrite procedure
CloseApplication method
Applies to
TReport component
Declaration
function CloseApplication(ShowDialogs: Boolean): Boolean;
The CloseApplication method stops ReportSmith Runtime, if it is running.
CloseApplication sends a DDE message to terminate ReportSmith Runtime and looks for
a DDE message from ReportSmith in return. If CloseApplication returns True, the
ReportSmith Runtime received the message to terminate successfully; if it returns False,
ReportSmith Runtime was not able to receive the message at the current time.
The value of the ShowDialogs parameter determines whether ReportSmith displays
dialog boxes prompting users to save the existing report before closing, and so on. If
ShowDialogs is True, the dialog boxes appear before ReportSmith closes. If the parameter
is False, no dialog boxes appear.
Declaration
procedure CloseDatabase(Database: TDatabase);
The CloseDatabase method closes a TDatabase component. The parameter Database
specifies the TDatabase component to close. Normally, this is handled automatically
when an application closes the last table in the database associated with a TDatabase
component. CloseDatabase decrements the Session’s reference count of the number of
open database connections.
You should always use CloseDatabase with OpenDatabase, typically in a try...finally block
to ensure that database connections are handled properly.
Example
Database := Session.OpenDatabase(‘DBDEMOS’);
try
begin
{Do Something}
finally
Session.CloseDatabase(‘DBDEMOS’);
end;
See also
Session variable
CloseDatasets method
Applies to
TDataBase component
Declaration
procedure CloseDatasets;
The CloseDatasets method closes all of the dataset components linked to the TDatabase
component, but does not close the database connection itself.
Example
Database1.CloseDatasets;
See also
Close method
CloseDialog method
Applies to
TFindDialog, TReplaceDialog components
Declaration
procedure CloseDialog;
The CloseDialog method closes the Find and Replace dialog boxes.
See also
Execute method
CloseLink method
Applies to
TDDEClientConv component
Declaration
function CloseLink;
The CloseLink method terminates an ongoing DDE conversation. After a link is closed,
+
no DDE communication can take place between the DDE client and server until another
link is opened.
+
Example
C
The following code terminates the DDE conversation.
DDEClientConv1.CloseLink;
See also
OnClose event, OpenLink method
CloseQuery method
Applies to
TForm component
Declaration
function CloseQuery: Boolean;
The CloseQuery method is called as part of a form’s Close method processing to
determine if the form can actually close. CloseQuery executes the code attached to the
OnCloseQuery event. If the OnCloseQuery event handler assigns False to its CanClose
parameter, CloseQuery will return False indicating that the form cannot close. Otherwise
CloseQuery returns True, indicating that the form is ready to close.
The CloseQuery method of the main form of an MDI application automatically calls the
CloseQuery method of each MDI child form before executing its own OnCloseQuery
event. If any of the child forms return False, the main form’s CloseQuery stops and also
returns False. Your application can use the OnCloseQuery event to ask users if they want
special processing to occur, such as saving information on the form, before the form is
closed.
Example
When the user attempts to close the form in this example, a message dialog appears that
asks if it is OK to close the form. If the user chooses No, the form doesn’t close. If the
user chooses OK, the form closes.
procedure TForm1.FormCloseQuery(Sender: TObject; var CanClose: Boolean);
var
ButtonSelected: Word;
begin
ButtonSelected := MessageDlg('Is it OK to close the form?', mtInformation,
[mbOk, mbNo], 0);
if ButtonSelected = mrOk then
CanClose := True
else
CanClose := False;
end;
See also
Close method, OnCloseQuery event
CloseReport method
Applies to
TReport component
Declaration
function CloseReport(ShowDialogs: Boolean): Boolean;
The CloseReport method determines whether the running of a ReportSmith report
terminates. CloseReport sends a DDE message to ReportSmith Runtime and looks for a
DDE message from ReportSmith Runtime in return. If CloseReport returns True,
ReportSmith Runtime received the message to terminate the report. If CloseReport
returns False, ReportSmith Runtime could not receive the DDE message at the current
time.
The ShowDialogs parameter determines whether dialog boxes that prompt the user
about saving the report appear before the report closes, and so on. If ShowDialogs is True,
the dialog boxes appear. If it is False, the dialog boxes are not shown.
Example
The following code terminates the running report if the user chooses Yes from a dialog
box:
if MessageDlg('Do you want to stop running ' + Report1.ReportName + ' ?',
mtConfirmation, [mbYes, mbNo], 0) = mrYes then
if Report1.CloseReport(False) then MessageDlg(Report1.ReportName + ' canceled.',
mtInformation, [mbOK], 0);
See also
CloseApplication method
CloseUp method
Applies to
TDBLookupCombo component
Declaration
procedure CloseUp;
The CloseUp method closes an opened or “dropped-down” database lookup combo box.
See also
DropDown method
Example
uses WinCrt;
begin
ClrScr;
Writeln('Hello there, how are you today?');
Writeln('Press <enter> key...');
Readln;
GotoXY(1,2);
ClrEol;
Writeln ('Glad to hear it!');
end;
See also
ClrScr procedure
Example
uses WinCrt;
begin
Writeln('Hello. Please the <enter> key...');
Readln;
ClrScr;
end;
See also
ClrEol procedure
Col property
Applies to
TDrawGrid, TStringGrid components
Declaration
property Col: Longint;
Run-time only. The value of the Col property indicates the current column of the cell that
has input focus. You can use the Col property along with the Row property to determine
which cell is selected at run time.
Example
This example uses a string grid with a label above it on a form. When the user clicks a
cell in the grid, the location of the cursor is displayed in the label caption.
procedure TForm1.StringGrid1Click(Sender: TObject);
begin
Label1.Caption := 'The cursor is in column ' + IntToStr(StringGrid1.Col + 1)
+ ', row ' + IntToStr(StringGrid1.Row + 1);
end;
See also
ColCount property, ColWidths property, DefaultColWidth property
Example
The following line of code adds one column to a string grid named MyStrngGrd:
MyStrngGrd.ColCount := MyStrngGrd.ColCount + 1;
See also
Col property, ColWidths property, RowCount property
Collapse method
Applies to
TOutlineNode object
Declaration
procedure Collapse;
The Collapse method collapses an outline item by assigning False to its Expanded
property. When an outline item is collapsed, its sub-items are hidden and the plus
picture or closed picture might be displayed, depending on the outline style specified in
the OutlineStyle property of the TOutline component.
Example
The following code collapses the first outline item.
Outline1.Items[1].Collapse;
See also
Expand method, FullCollapse method, FullExpand method, PictureClosed property,
PicturePlus property
Collate property
Applies to
TPrintDialog component
Declaration
property Collate: Boolean;
The Collate property determines if the Collate check box is checked and, therefore, if
collating is selected. Regardless of the initial setting of the Collate property, the user can
always check or uncheck the Collate check box (and change the Collate property) to
choose or not choose to collate the print job. The default setting is False.
Color property
Applies to
TBrush, TFont, TPen objects; TBitBtn, TCheckBox, TColorDialog, TComboBox,
TDBCheckBox, TDBComboBox, TDBEdit, TDBGrid, TDBImage, TDBListBox,
TDBLookupCombo, TDBLookupList, TDBMemo, TDBRadioGroup, TDBText,
TDirectoryListBox, TDrawGrid, TDriveComboBox, TEdit, TFileListBox, TForm, TGroupBox,
TLabel, TListBox, TMaskEdit, TMemo, TNotebook, TOutline, TPaintBox, TPanel,
TRadioButton, TScrollBox, TStringGrid components
Declaration
property Color: TColor;
For all components or objects except the Color dialog box, the Color property determines
the background color of a form or the color of a control or graphics object.
If a control’s ParentColor property is True, then changing the Color property of the
control’s parent automatically changes the Color property of the control. When you
assign a value to a control’s Color property, the control’s ParentColor property is
automatically set to False. These are the possible values of Color:
Value Meaning
clBlack Black
clMaroon Maroon
clGreen Green
clOlive Olive green
clNavy Navy blue
clPurple Purple
clTeal Teal
clGray Gray
clSilver Silver
clRed Red
clLime Lime green
clBlue Blue
clFuchsia Fuchsia
clAqua Aqua
clWhite White
clBackground Current color of your Windows background
The second half of the colors listed here are Windows system colors. The color that
appears depends on the color scheme users are using for Windows. Users can change
these colors using the Control Panel in Program Manager. The actual color that appears
will vary from system to system. For example, the color fuchsia may appear more blue
on one system than another.
Example
This code colors a form red:
Form1.Color := clRed;
The following code changes the color of an edit box control using the Color dialog box.
The example displays the Color dialog box when the Button1 button is clicked, allowing
the user to select a color with the dialog box. The example then assigns the color value
selected with the dialog box to the Color property of the edit box control:
procedure TForm1.Button1Click(Sender: TObject);
begin
if ColorDialog1.Execute then
Edit1.Color := ColorDialog1.Color;
end;
See also
ColorToRGB function, ParentColor property, TColorDialog component
ColoredButtons property
Applies to
TMediaPlayer component
Declaration
property ColoredButtons: TButtonSet;
The ColoredButtons property determines which of the buttons on the media player
control has color. If a button is not colored with ColoredButtons, it appears in black-and-
white when visible. All media player control buttons are colored by default.
Example
The following example displays all of the media player component’s buttons in color:
TMediaPlayer1.ColoredButtons := [btPlay, btPause, btStop, btNext, btPrev, btStep, btBack,
btRecord, btEject]
See also
EnabledButtons property, VisibleButtons property
The ColorToRGB function returns the RGB value that Windows uses from a TColor type
+
used by Delphi. If the color represents a system color, the current RGB value for that
system color is returned.
+
Example
C
The following code converts the color of the current form, Form1, to a Windows RGB
value:
var
L : Longint;
begin
L := ColorToRGB(Form1.Color);
end;
See also
Color property
Cols property
Applies to
TStringGrid component
Declaration
property Cols[Index: Integer]: TStrings;
The Cols property is an array of the strings and their associated objects in a column. The
number of strings and associated objects is always equal to the value of the ColCount
property, the number of columns in the grid. Use the Cols property to access the strings
and their associated objects within a particular column in the grid. The Index parameter
is the number of the column you want to access; the Index value of the first column in the
grid is zero.
Example
The following line of code adds the string ’Hello’ to the end of the list of strings in
column four of the string grid named StringGrid1:
StringGrid1.Cols[3].Add('Hello');
See also
Cells property, Objects property, Rows property
Columns property
Applies to
TDBRadioGroup, TDirectoryListBox, TListBox, TRadioGroup components
Declaration
property Columns: Longint;
The Columns property denotes the number of columns in the list box or radio group box.
Specify the number of columns you want for the list box or radio group box as the value
of Columns.
Example
This example uses a list box and a button on a form. Each time the user clicks the button,
the string ‘Hello’ is added to the list box. When the list box is filled, a new column is
created and subsequent new strings are added to the new column:
procedure TForm1.Button1Click(Sender: TObject);
begin
if ListBox1.Columns < 1 then
ListBox1.Columns := 1;
Listbox1.Items.Add('Hello');
if Listbox1.Height <= ((Listbox1.ItemHeight * Listbox1.Items.Count)
/ ListBox1.Columns) then
Listbox1.Columns := Listbox1.Columns + 1;
end;
ColWidths property
Applies to
TDrawGrid, TStringGrid components
Declaration
property ColWidths[Index: Longint]: Integer;
Run-time only. The ColWidths property determines the width in pixels of all the cells
within the column referenced by the Index parameter.
By default, all the columns are the same width, the value of the DefaultColWidth
property. To change the width of all columns within a grid, change the DefaultColWidth
property value.
To change the width of one column without affecting others, change the ColWidths
property. Specify the column you want to change as the value of the Index parameter.
Remember the first column always has an Index value of 0.
Example
The following code changes the width of column 0 in the string grid called StringGrid1
to twice the default value.
StringGrid1.ColWidths[0] := StringGrid1.DefaultColWidth * 2;
See also
RowHeights property
Example
The following procedure is a WM_COMMAND message handler. It checks the ItemID
field of Msg to see if the message was generated by a menu item called MenuThink. If so,
it displays a message dialog box. When writing message handlers, remember to call
Inherited afterward, if necessary, so Windows can perform default message processing.
procedure TForm1.WMCommand(var Msg: TWMCommand);
begin
if Msg.ItemID = MenuThink.Command then
MessageDlg(‘This is the Think command’, mtInformation, [mbOk], 0);
Inherited;
end;
Commit method
Applies to
TDataBase component
Declaration
procedure Commit;
The Commit method commits the current transactions and thus all modifications made
to the database since the last call to StartTransaction. If no transaction is active, Delphi
will raise an exception. Use this method only when connected to a server database.
Example
with Database1 do
begin
StartTransaction;
{ Update one or more records in tables linked to Database1 }
...
Commit;
end;
See also
Rollback method
Example
The following code compares String1, 'STEVE', to String2, 'STEVe'. Note that CompareStr
returns a number less than 0 because the value of 'e' is greater than the value of 'E'.
var
String1, String2 : string;
I : integer;
begin
String1 := 'STEVE';
String2 := 'STEVe';
I := CompareStr(String1, String2); { the value of I is < 0 }
if I < 0 then
MessageDlg('The strings are not equal', mtWarning, [mbOK], 0)
end;
See also
CompareText function
Example
The following code compares String1, 'ABC, to String2, 'aaa'. Because CompareText is
case insensitive, String2 is larger.
var
String1, String2 : string;
See also
CompareStr function
ComponentCount property
Applies to
All components
Declaration
property ComponentCount: Integer;
Run-time and read only. The ComponentCount property indicates the number of
components owned by the component as listed in the Components array property. For
example, ComponentCount of a form contains the same number of items as in the
Components list of a form.
Note ComponentCount is always 1 more than the highest Components index, because the first
Components index is always 0.
Example
This code uses several controls on a form, including a button and an edit box. When the
user clicks the button, the code counts all the components on the form and displays the
number in the Edit1 edit box. While the components are being counted, each is
evaluated to see if it is a button component. If the component is a button, the code
changes the font on the button face.
procedure TForm1.Button1Click(Sender: TObject);
var
I: Integer;
begin
for I := 0 to ComponentCount -1 do
if Components[I] is TButton then
TButton(Components[I]).Font.Name := 'Courier';
Edit1.Text := IntToStr(ComponentCount) + ' components';
end;
See also
ComponentIndex property, Components property
ComponentIndex property
Applies to
All components
Declaration
property ComponentIndex: Integer;
Run-time and read only. The ComponentIndex property indicates the position of the
component in its owner’s Components property list. The first component in the list has a
ComponentIndex value of 0, the second has a value of 1, and so on.
Example
The following code uses a button and a wide edit box on a form. When the user clicks
the button, the edit box displays the index value of the button component:
procedure TForm1.Button1Click(Sender: TObject);
begin
Edit1.Text := 'The index of the button is ' + IntToStr(Button1.ComponentIndex);
end;
See also
ComponentCount property, Components property
Components property
Applies to
All components
Declaration
property Components[Index: Integer]: TComponent;
Run-time and read only. The Components array property is a list of all components
owned by the component. You can use the Components property to access any of these
owned components, such as the controls owned by a form. The Components property is
most useful if you need to refer to owned components by number rather than name.
Don’t confuse the Components property with the Controls property. The Components
property lists all components that are owned by the component, whereas the Controls
property lists all the controls that are child windows of this control. All components on a
form are owned by the form, and therefore, they appear in the form’s Components
property list.
Consider this example. If you put a control in a group box, the form still owns the
control, but the control’s window parent is the group box control, and therefore, is listed
in the group box’s Controls property array.
See also
ComponentCount property, ComponentIndex property, Owner property, Parent property,
TabOrder property
Example
var
S: string;
begin
S := Concat('ABC', 'DEF'); { 'ABCDE' }
end;
See also
Copy function, Delete procedure, Insert procedure, Length function, Pos function
ConfirmDelete property
Applies to
TDBNavigator component
Declaration
property ConfirmDelete: Boolean;
The ConfirmDelete property determines whether a message box asking you to confirm
the deletion when the user uses the database navigator to delete the current record in
the dataset. If ConfirmDelete is True, a prompting message box appears and the record
isn’t deleted unless the user chooses the OK button. If ConfirmDelete is False, no message
box appears and the record is deleted.
The default value is True.
See also
VisibleButtons property
Connect method
Applies to
TReport component
Declaration
function Connect(ServerType: Word; const ServerName, UserName, Password,
DatabaseName: string): Boolean;
The Connect method connects the report to a database, bypassing the ReportSmith log in
dialog box. Specify the server type and name with the ServerType and ServerName
parameters. Specify the user name, the log-in password, and the name of the database
using the UserName, Password, and DatabaseName parameters.
Connected property
Applies to
TDataBase component
Declaration
property Connected: Boolean;
The Connected property indicates whether the TDatabase component has established a
connection to a database. Connected will be set to True when an application opens a table
in a database (logging in to a server, if required). It will be set back to False when the
table is closed (unless KeepConnection is True). Set Connected to True to establish a
Example
Database1.Connected := True;
ConnectMode property
Applies to
TDDEClientConv component
Declaration
property ConnectMode: TDataMode;
The ConnectMode property determines the type of connection to establish when
initiating a link with a DDE server application. These are the possible values:
Value Meaning
ddeAutomatic The link is automatically established when the form containing the TDDEClient
component is created at run time. This is the default value.
ddeManual The link is established only when the OpenLink method is called.
Example
The following code sets the connect mode of DDEClientConv1 to manual.
DDEClientConv1.ConnectMode := ddeManual;
ContainsControl method
Applies to
All windowed controls
Declaration
function ContainsControl(Control: TControl): Boolean;
The ContainsControl method indicates whether a specified control exists within a control.
If the method returns True, the control specified as the value of the Control parameter
exists within the control. If the method returns False, the specified control is not within
the control.
Example
This example uses a label, a list box, and a button on a form. When the user clicks the
button, the caption of the label reports that the form contains the list box:
procedure TForm1.Button1Click(Sender: TObject);
begin
if ContainsControl(ListBox1) then
Label1.Caption := 'The form contains ListBox1';
end;
Example
var
F: File;
i: integer;
begin
for i := 0 to (FileListBox1.Items.Count – 1) do begin
if FileListBox1.Selected[i] then begin
if not FileExists(FileListBox1.Items.Strings[i]) then begin
MessageDlg('File: ' + FileListBox1.Items.Strings[i] +
' not found', mtError, [mbOk], 0);
Continue;
end;
AssignFile(F, FileListBox1.Items.Strings[i]);
Reset(F, 1);
ListBox1.Items.Add(IntToStr(FileSize(F)));
CloseFile(F);
end;
end;
end;
See also
Break procedure, Exit procedure, Halt procedure
ControlCount property
Applies to
All controls
Declaration
property ControlCount: Integer;
Run-time and read only. The ControlCount property indicates the number of controls
that are children of the control. The children are listed in the Controls property array.
Note The value of ControlCount is always 1 greater than the highest Controls index, because
the first Controls index is 0.
Example
This example uses a group box on a form, with several controls contained within the
group box. The form also has an edit box and a button outside of the group box. The
code counts each control’s child controls turning each of them invisible as they are
counted. The total number of controls counted appears in the edit box.
procedure TForm1.Button1Click(Sender: TObject);
var
I: Integer;
begin
for I:= 0 to GroupBox1.ControlCount -1 do
GroupBox1.Controls[I].Visible := False;
Edit1.Text := IntToStr(GroupBox1.ControlCount) + ' controls';
end;
See also
Controls property
Controls property
Applies to
All controls
Declaration
property Controls[Index: Integer]: TControl;
Run-time and read only. The Controls property is an array of all controls that are
children of the control. The Controls property is most useful if you have a need to refer to
the children of a control by number rather than name.
Don’t confuse the Controls property with the Components property. The Components
property lists all components that are owned by the component, while the Controls
property lists all the controls that are child windows of the control. All components put
on a form are owned by the form, and therefore, they appear in the form’s Components
property list.
For example, if you put a control in a group box, the form still owns the control, but the
control’s window parent is the group box control, and therefore, is listed in the group
box’s Controls property array.
Example
This example uses a group box on a form, with several controls contained within the
group box. The form also has an edit box and a button outside of the group box. The
code counts each control’s child controls turning each of them invisible as they are
counted. The total number of controls counted displays in the edit box.
procedure TForm1.Button1Click(Sender: TObject);
var
I: Integer;
begin
for I:= 0 to GroupBox1.ControlCount -1 do
GroupBox1.Controls[I].Visible := False;
Edit1.Text := IntToStr(GroupBox1.ControlCount) + ' controls';
end;
See also
ControlCount property, Owner property, Parent property
ConvertDlgHelp property
Applies to
TOLEContainer component
Declaration
property ConvertDlgHelp: THelpContext;
Example
The following code assigns 531 to the context-sensitive Help identification number of
the OLE Convert dialog box.
OLEContainer1.ConvertDlgHelp := 531;
Copies property
Applies to
TPrintDialog component
Declaration
property Copies: Integer;
The value of the Copies property determines the number of copies of the print job to
print. If you change the value of Copies at design time, the value you specify is the
default value in the edit box control when the Print dialog box appears. The default
value is 0.
Example
The following code sets the default number of copies for the print dialog box,
PrintDialog1, to 3 before displaying the dialog box:
PrintDialog1.Copies := 3;
PrintDialog1.Execute;
Example
var S: string;
begin
S := 'ABCDEF';
S := Copy(S, 2, 3); { 'BCD' }
end;
See also
Concat function, Delete procedure, Insert procedure, Length function, Pos function
CopyMode property
Applies to
TCanvas object
Declaration
property CopyMode: TCopyMode;
The CopyMode property determines how a canvas treats an image copied from another
canvas. By default, CopyMode is cmSrcCopy, meaning that pixels from the other canvas
are copied to the canvas, overwriting any image already there. By changing CopyMode,
you can create many different effects. The following table shows possible values of
CopyMode and describes each:
Value Meaning
cmBlackness Turns all output black.
cmDstInvert Inverts the destination bitmap.
cmMergeCopy Combines the pattern and the source bitmap by using the Boolean AND operator.
cmMergePaint Combines the inverted source bitmap with the destination bitmap by using the
Boolean OR operator.
cmNotSrcCopy Copies the inverted source bitmap to the destination.
Example
The following code copies the the inverted source bitmap to the Canvas of Form2:
Form2.Canvas.CopyMode := cmNotSrcCopy;
Form2.Canvas.CopyRect(ClientRect, Canvas, ClientRect);
See also
CopyRect method
CopyParams method
Applies to
TStoredProc component
Declaration
procedure CopyParams(Value: TParams);
The CopyParams method copies all of the parameter information from the stored
procedure component to Value. Use this method to copy parameters from one stored
procedure component to another.
Example
{ Copy all parameters from StoredProc1 to StoredProc2 }
StoredProc1.CopyParams(StoredProc2.Params);
CopyRect method
Applies to
TCanvas object
Declaration
procedure CopyRect(Dest: TRect; Canvas: TCanvas; Source: TRect);
The CopyRect method copies part of an image from another canvas into the canvas
object. The Dest property specifies the destination rectangle on the destination canvas
where the image will be copied. The Canvas property specifies the source canvas. The
Source property specifies the source rectangle from the source canvas that will be copied.
Example
The following code copies the the inverted source bitmap to the Canvas of Form2:
Form2.Canvas.CopyMode := cmNotSrcCopy;
Form2.Canvas.CopyRect(ClientRect, Canvas, ClientRect);
See also
CopyMode property
CopyToClipboard method
Applies to
TDBEdit, TDBImage, TDBMemo, TDDEServerItem, TEdit, TMemo, TOLEContainer
components
Example
The following method copies the selected text from the memo control named Memo1 to
the Clipboard and pastes it into an edit box named Edit1 when the user clicks the button
named Button1:
procedure TForm1.Button1Click(Sender: TObject);
begin
Memo1.CopyToClipboard;
Edit1.PasteFromClipboard;
end;
Example
The following code copies the OLE object in OLEContainer1 to the Clipboard without
clearing the contents first.
OLEContainer1.CopyToClipboard(False);
See also
Clear method
rules of the DDE server application. See the documentation for the DDE server
application for specific information about pasting the link.
If the Clear parameter is True, the prior contents of the Clipboard are deleted before
CopyToClipboard places its data on the Clipboard. If Clear is False, the Clipboard won’t be
cleared before the copy.
Example
The following code copies the DDE link information of DDEServerItem1 to the
Clipboard, clearing the contents of the Clipboard before the copy.
DDEServerItem1.CopyToClipboard;
See also
Clear method
Example
The following code copies the contents of DBImage1 to the Clipboard without clearing
the contents of the Clipboard first.
DBImage1.CopyToClipboard(False);
See also
CutToClipboard method, PasteFromClipboard method
Example
var R: Real;
begin
R := Cos(Pi);
end;
Example
The following code displays the number of items in a list box in the caption of a label
when the user clicks the CountItems button:
procedure TForm1.CountItemsClick(Sender: TObject);
begin
Label1.Caption := 'There are ' + IntToStr(ListBox1.Items.Count) +
' items in the listbox.';
end;
The following example assumes the form contains a main menu component, which
includes a File menu and a label. This code displays the number of menu items that
make up the File menu.
procedure TForm1.Button1Click(Sender: TObject);
begin
Label1.Caption := IntToStr(FileMenu.Count):
end;
See also
Items property, List property, Strings property
Example
{ Assign 99999 to any integer parameter which does not have a value }
for I := 0 to Params.Count - 1 do
if (Params.Items[I].IsNull) and (Params.Items[I].DataType = ftInteger) then
{ Items is the default property, so you can omit its name }
Params[I].AsInteger := 99999;
See also
Items property
Create method
Applies to
All objects and components
Example
This code creates an .INI file object and passes it the name of the .INI file,
SUPERAPP.INI:
var
IniFile: TIniFile;
begin
IniFile := TIniFile.Create(‘SUPERAPP.INI’);
IniFile.Free;
end;
Example
{ Link BlobStream1 to MyBlobField for data access only }
BlobStream1 := TBlobStream.Create(MyBlobField, bmRead);
Example
The following code creates a TButton and makes Form1 the owner.
var
Button1: TButton;
begin
Button1 := TButton.Create(Form1);
end;
Example
The following code creates a TBitmap and loads the bitmap graphic file C:\WINDOWS\
256COLOR.BMP into it. Then, the bitmap is drawn in a paint box by the OnPaint event
handler of PaintBox1.
procedure TForm1.PaintBox1Paint(Sender: TObject);
var
Bitmap1: TBitmap;
begin
Bitmap1 := TBitmap.Create;
Bitmap1.LoadFromFile('c:\windows\256color.bmp');
PaintBox1.Canvas.Draw(0, 0, Bitmap1);
Bitmap1.Free;
end;
See also
Free method
CreateField method
Applies to
TFieldDef object
Declaration
function CreateField(Owner: TComponent): TField;
CreateField creates a TField component of the appropriate type that corresponds to the
TFieldDef object itself. Owner is the dataset component containing the field.
CreateForm method
Applies to
TApplication component
Declaration
procedure CreateForm(FormClass: TFormClass; var Reference);
The CreateForm method creates a new form of the type specified by the FormClass
parameter and assigns it to the variable given by the Reference parameter. The owner of
the new form is the Application object. The form created by the first call to CreateForm in a
project becomes the project's main form.
A Delphi project typically contains one or more calls to CreateForm in the project's main
statement part, but there is seldom any need for you to call CreateForm yourself.
Example
The following code creates Form1 of type TForm1.
Application.CreateForm(TForm1, Form1);
CreateNew method
Applies to
TForm component
Declaration
constructor CreateNew(AOwner: TComponent);
The CreateNew method creates a new instance of the current form type.
CreateParam method
Applies to
TParams object
Declaration
function CreateParam(FldType: TFieldType; const ParamName: string;
ParamType: TParamType): TParam;
The CreateParam method attempts to create a new entry in Items, using the FieldType,
ParamName, and ParamType parameters.
Example
{ Create a new parameter for CustNo and assign a value of 999 to it }
with Params.CreateParam(ftInteger, ‘CustNo’, ptInput) do
AsInteger := 999;
Example
with Table1 do
begin
Active := False;
DatabaseName := ‘Delphi_Demos’;
TableName := ‘CustInfo’;
TableType := ttParadox;
with FieldDefs do
begin
Clear;
Add(‘Field1’, ftInteger, 0);
Add(‘Field2’, ftInteger, 0);
end;
with IndexDefs do
begin
Clear;
Add(‘Field1Index’, ‘Field1’, [ixPrimary, ixUnique]);
end;
CreateTable;
end;
Example
function MakeHexWord(w: Word): string;
const
hexChars: array [0..$F] of Char = '0123456789ABCDEF';
var
HexStr : string;
begin
HexStr := '';
HexStr := HexStr + hexChars[Hi(w) shr 4];
HexStr := HexStr + hexChars[Hi(w) and $F];
HexStr := HexStr + hexChars[Lo(w) shr 4];
HexStr := HexStr + hexChars[Lo(w) and $F];
MakeHexWord := HexStr;
end;
procedure TForm1.Button1Click(Sender: TObject);
var
i: Integer;
Y: Integer;
S: string;
begin
Y := 10;
S := 'The current code segment is $' + MakeHexWord(CSeg);
Canvas.TextOut(5, Y, S);
Y := Y + Canvas.TextHeight(S) + 5;
S := 'The global data segment is $' + MakeHexWord(DSeg);
Canvas.TextOut(5, Y, S);
Y := Y + Canvas.TextHeight(S) + 5;
S := 'The stack segment is $' + MakeHexWord(SSeg);
Canvas.TextOut(5, Y, S);
Y := Y + Canvas.TextHeight(S) + 5;
S := 'The stack pointer is at $' + MakeHexWord(SPtr);
Canvas.TextOut(5, Y, S);
Y := Y + Canvas.TextHeight(S) + 5;
S := 'i is at offset $' + MakeHexWord(Ofs(i));
Canvas.TextOut(5, Y, S);
Y := Y + Canvas.TextHeight(S) + 5;
S := 'in segment $' + MakeHexWord(Seg(i));
Canvas.TextOut(5, Y, S);
end;
See also
DSeg function, SSeg function
Ctl3D property
Applies to
TBitBtn, TButton, TCheckBox, TColorDialog, TComboBox, TDBCheckBox, TDBComboBox,
TDBEdit, TDBGrid, TDBImage, TDBListBox, TDBLookupCombo, TDBLookupList,
TDBMemo, TDBNavigator, TDBRadioGroup, TDirectoryListBox, TDrawGrid,
TDriveComboBox, TEdit, TFileListBox, TFindDialog, TFilterComboBox, TFontDialog, TForm,
TGroupBox, TListBox, TMaskEdit, TMemo, TNotebook, TOLEContainer, TOpenDialog,
TOutline, TPanel, TRadioButton, TReplaceDialog, TSaveDialog, TScrollBar, TScrollBox,
TStringGrid components
Example
The following code toggles the 3-D look of a memo control when the user clicks a button
named Toggle:
procedure TForm1.ToggleClick(Sender: TObject);
begin
Memo1.Ctl3D := not Memo1.Ctl3D; {Toggles the Ctl3D property of Memo1}
end;
See also
ParentCtl3D property
TimePMString: string[7];
ShortTimeFormat: string[15];
LongTimeFormat: string[31];
ShortMonthNames: array[1..12] of string[3];
LongMonthNames: array[1..12] of string[15];
ShortDayNames: array[1..7] of string[3];
LongDayNames: array[1..7] of string[15];
The SysUtils unit includes a number of variables that are used by the date and time
routines. You can assign new values to these variables to change the formats of date and
time strings.
The initial value is fetched from the iCurrency variable in the [intl] section of
WIN.INI.
NegCurrFormat The currency format for used in floating-point to decimal conversions of
negative numbers. Possible values are:
0 = ($1) 4 = (1$)
1 = -$1 5 = -1$
2 = $-1 6 = 1-$
3 = $1- 7 = 1$-
The initial value is fetched from the iNegCurr variable in the [intl] section of
WIN.INI.
ThousandSeparator The character used to separate thousands in numbers with more than three digits
to the left of the decimal separator. The initial value is fetched from the
sThousand variable in the [intl] section of WIN.INI.
DecimalSeparator The character used to separate the integer part from the fractional part of a
number. The initial value is fetched from the sDecimal variable in the [intl]
section of WIN.INI.
CurrencyDecimals The number of digits to the right of the decimal point in a currency amount. The
initial value is fetched from the sCurrDigits variable in the [intl] section of
WIN.INI.
DateSeparator The character used to separate the year, month, and day parts of a date value.
The initial value is fetched from the sDate variable in the [intl] section of
WIN.INI.
Example
This example uses a label and a button on a form. When the user clicks the button, the
current date displays in the caption of the label. Because some of the date variables are
assigned new values, the format of the date in the label changes. For example, if the date
is 9/15/94, the date displays as 15-09-1994.
procedure TForm1.Button1Click(Sender: TObject);
begin
DateOrder := doDMY;
DateSeparator := '-';
DateFullYear := True;
DateLeadZero := True;
Label1.Caption := DateToStr(Date);
end;
Currency property
Applies to
TBCDField, TCurrencyField, TFloatField components
Declaration
property Currency: Boolean;
Run-time only. The Currency property is used to control the format of the value of a
TBCDField, TCurrencyField, and TFloatField when both DisplayFormat and EditFormat
properties are not assigned.
Currency is True by default for TCurrencyField and False for TFloatField and TBCDField.
When Currency is True formatting is performed by FloatToText using ffCurrency for
display text or ffFixed for editable text. When Currency is False, the formatting is
performed by FloatToTextFmt.
See also
DisplayFormat property, EditFormat property, FloatToText function, FloatToTextFmt
function
Cursor property
Applies to
All controls, TScreen component
Example
This line of code changes the display of the image to the cross cursor when the user
moves the mouse pointer over Button1:
Button1.Cursor := crCross;
See also
Cursors property, DragCursor property
Declaration
property Cursor: TCursor;
The Screen object's Cursor property controls the mouse cursor shape at a global level.
Assigning any value but crDefault to the Screen object's Cursor property sets the mouse
cursor shape for all windows belonging to the application. The global mouse cursor
shape remains in effect until you assign crDefault to the Screen object's Cursor property,
at which point normal cursor behavior is restored.
To see a list of possible cursor shapes, see the Cursor property for all controls.
Example
Assignments to the Screen object's cursor property are typically guarded by a
try...finally statement to ensure that normal cursor behavior is restored, for example:
Screen.Cursor := crHourglass; { Show hourglass cursor }
try
{ Do some lengthy operation }
finally
Screen.Cursor := crDefault; { Always restore to normal }
end;
CursorPosChanged method
Applies to
TTable, TQuery, TStoredProc components
Declaration
procedure CursorPosChanged;
The CursorPosChanged method is needed only if you use the Handle property to make
direct calls to the Borland Database Engine (BDE) API which cause the cursor position
to change. To notify the dataset that the underlying BDE cursor’s position has changed,
call CursorPosChanged after the direct calls to the BDE.
See also
UpdateCursorPos method
Cursors property
Applies to
TScreen component
Declaration
property Cursors[Index: Integer]: HCursor;
Run-time only. The Cursors property gives you access to the list of cursors available for
your application. To access a particular cursor, specify its position in the list of cursors as
the value of the Index parameter with the first position in the list having an index of 0,
the second having an index of 1, and so on.
Using the Cursors property, you can make custom cursors available to your application.
These are the cursor constants and their position in the Cursors property array:
+
Cursor Value Cursor Value
+
crDefault
crNone
0
–1
crSizeWE
crUpArrow
–9
–10
C
crArrow –2 crHourglass –11
crCross –3 crDrag –12
crIBeam –4 crNoDrop –13
crSize –5 crHSplit –14
crSizeNESW –6 crVSplit –15
crSizeNS –7 crMultiDrag –16
crSizeNWSE –8 crSQLWait –17
Example
This example assumes you have created a cursor resource with the name NewCursor.
The code loads the new cursor into the Cursors property array and makes the newly
loaded cursor the cursor of the form:
const
crMyCursor = 5;
procedure TForm1.FormCreate(Sender: TObject);
begin
Screen.Cursors[crMyCursor] := LoadCursor(HInstance, 'NewCursor');
Cursor := crMyCursor;
end;
See also
Cursor property, DragCursor property
The CursorTo procedure moves the cursor to the given coordinates (X, Y) within the
virtual screen.
The coordinates of the upper left corner of the CRT window are (0, 0). CursorTo sets the
Cursor variable to (X, Y).
See also
GoToXY procedure
CustomColors property
Applies to
TColorDialog component
Declaration
property CustomColors: TStrings;
The value of the CustomColors property determines the custom colors that are available
in the Color dialog box. Each custom color is represented as a string that follows this
format:
ColorX=HexValue
For example, this string could indicate that the first custom color box in the Color dialog
box:
ColorA=808022
This is the same format that your CONTROL.INI file uses to specify the custom colors
that are available in the Windows Color dialog box.
You can have up to 16 custom colors, ColorA through ColorP.
Use the string list of custom colors to save the custom colors specified in the dialog box
so you can use them elsewhere. For example, you might save them to an .INI file for
your application so your application can use the custom colors.
Example
This example displays the Color dialog box, allowing the user to create custom colors,
then displays the custom color strings in a list box:
procedure TForm1.Button1Click(Sender: TObject);
begin
if ColorDialog1.Execute then
ListBox1.Items.AddStrings(ColorDialog1.CustomColors);
end;
Example
The following method cuts the text the user selects in Memo1 to the Clipboard and
pastes it from the Clipboard in an edit box control when the user clicks the button:
procedure TForm1.Button1Click(Sender: TObject);
begin
Memo1.CutToClipboard;
Edit1.PasteFromClipboard;
end;
See also
Clear method, ClearSelection method, CopyToClipboard method, PasteFromClipboard
method
Data property
Applies to
TOutlineNode component
Declaration
property Data: Pointer;
Run-time only. The Data property specifies any data you want associated with an
outline item.
Example
The following code creates a TBitmap and adds it to the Data of the selected outline item.
var
Bitmap: TBitmap;
begin
Bitmap := TBitmap.Create;
Outline1.Items[Outline1.SelectedItem].Data := Bitmap;
end;
See also
GetDataItem method, Text property
Database property
Applies to
TTable, TQuery component
Declaration
property Database: TDatabase;
Run-time and read only. Database specifies the database (TDatabase) component
associated with the dataset component. If you did not create a TDatabase at design time,
then Delphi will create one at run time. Use the Database property to reference the
properties and methods of the database.
Example
{ Do a transaction }
with Table1.Database do
begin
StartTransAction;
{ Post some records with Table1 }
Commit;
end;
DatabaseCount property
Applies to
TSession component
Declaration
property DatabaseCount: Integer;
Run-time and read only. DatabaseCount is the number of TDataBase components
currently attached to Session.
Example
{ Close all databases }
with Session do
while DatabaseCount <> 0 do
Databases[0].Close;
Example
{ Test for an error and raise an exception if so }
if { some error has occured } then DatabaseError(‘Some error has occured’);
DatabaseName property
Applies to
TDataBase, TQuery, TStoredProc, TTable components
Example
Database1.DatabaseName := ‘Delphi_Demos’;
Set the DatabaseName property to specify the database to access. This property can
specify:
• A defined BDE alias,
• A directory path for desktop database files,
• A directory path and file name for a Local InterBase Server database,
• An application-specific alias defined by a TDatabase component
Note Use the Close method to put a dataset in Inactive state before changing DatabaseName.
Example
{ Close the DBDataSet }
Table1.Active := False;
try
{ First try to use an alias }
Table1.DatabaseName := ‘Delphi_Demos’;
Table1.Active := True;
except
on EDatabaseError do
{ If that fails, try to use the drive and directory }
Table1.DatabaseName := ‘c:\delphi\demos\database’;
Table1.Active := True;
See also
Active property
Databases property
Applies to
TSession component
Declaration
property Databases[Index: Integer]: TDatabase;
Run-time and read only. The Databases property holds a list of all of the currently active
TDatabase components.
Example
{ Close all databases }
with Session do
while DatabaseCount <> 0 do
Databases[0].Close;
See also
DatabaseCount property
Example
The following code specifies that the DataField of DBEdit1 is ‘FNAME’.
DBEdit1.DataField := ‘FNAME’;
DataFormat property
Applies to
TOLEDropNotify object
Declaration
property DataFormat: Word;
The DataFormat property specifies the Clipboard format of data dropped on a form. The
form must be registered with the RegisterFormAsOLEDropTarget function for a
TOLEDropNotify object to be the Source in an OnDragDrop event handler. If DataFormat
specifies an OLE object format, the PInitInfo property points to initialization information
for the dropped OLE object. If the dropped data is not an OLE object, DataFormat
specifies some other format (such as CF_BITMAP for bitmap graphic data) and PInitInfo
won’t point to valid OLE initialization information and can’t be used to initialize a
TOLEContainer component.
Example
The following code is the OnDragDrop event handler for a form that is registered as an
OLE drop target with RegisterFormAsOLEDropTarget. If a text object is dropped, a label is
created to display the data. If a metafile object is dropped, an image is created to display
the data. Otherwise, it is assumed that an OLE object was dropped and an OLE
container is created to contain the object.
See also
DataHandle property
DataHandle property
Applies to
TOLEDropNotify object
Declaration
property DataHandle: THandle;
The DataHandle property specifies a handle to the data dropped on a form. The form
must have been registered with the RegisterFormAsOLEDropTarget function for a
TOLEDropNotify object to be the Source in an OnDragDrop event handler. If the data is
any type other than an OLE object, you can use DataHandle to access the data.
Example
The following code locks the data handle of a TOLEDropNotify object named Dropper.
Ptr := GlobalLock (Dropper.DataHandle);
See also
DataFormat property
DataSet property
Applies to
TBCDField, TBlobField, TBooleanField, TBytesField, TCurrencyField, TDataSource,
TDateField, TDateTimeField, TFloatField, TGraphicField, TIntegerField, TMemoField,
TSmallintField, TStringField, TTimeField, TVarBytesField, TWordField components
DataSet specifies the dataset component (TTable, TQuery, and TStoredProc) that is
providing data to the data source. Usually you set DataSet at design time with the Object
Inspector, but you can also set it programmatically. The advantage of this interface
approach to connecting data components is that the dataset, data source, and data-
aware controls can be connected and disconnected from each other through the
TDataSource component. In addition, these components can belong to different forms.
Example
DataSource1.DataSet := Table1; {get data from this form’s Table1}
DataSource1.DataSet := Form2.Table1; {get data from Form2’s Table1}
DatasetCount property
Applies to
TDataBase component
Declaration
property DatasetCount: Integer;
DatasetCount is the number of dataset components (TTable, TQuery, and TStoredProc)
that are currently using the TDatabase component. Read-only and run time only.
Example
{ Check to see if any record associated with this database has pending updates }
Changed := False;
with Database1 do
for I := 0 to DatasetCount - 1 do
Changed := Changed or DataSets[I].Modified;
See also
Datasets property
Example
{ Check to see if any record associated with this database has pending updates }
Changed := False;
with Database1 do
for I := 0 to DatasetCount - 1 do
Changed := Changed or DataSets[I].Modified;
See also
DatasetCount property
DataSize property
Applies to
TBCDField, TBlobField, TBooleanField, TBytesField, TCurrencyField, TDateField,
TDateTimeField, TFloatField, TGraphicField, TIntegerField, TMemoField, TSmallintField,
TStringField, TTimeField, TVarBytesField, TWordField components
Declaration
property DataSize: Word;
Run-time and read only. The value of DataSize is the number of bytes required to store
the field in memory.
For TBoolean, TSmallint, and TWordField, the value is two bytes. For TDateField,
TIntegerField, and TTimeField, the value is four bytes. For TCurrencyField, TDateTimeField,
and TFloatField, the value is eight bytes. For TBCDField, the value is eighteen bytes. For
TStringField, the value is the maximum size of the text plus one (not more than 255
characters). For TBlobField, TBytesField, TGraphicField, TMemoField, and TVarBytesField,
the value is the size of the field as stored in the record buffer.
DataSource property
Applies to
TDBCheckBox, TDBComboBox, TDBEdit, TDBGrid, TDBImage, TDBListBox,
TDBLookupCombo, TDBLookupList, TDBMemo, TDBNavigator, TQuery, TDBRadioGroup,
TDBText components
Declaration
property DataSource: TDataSource;
The DataSource property determines where the component obtains the data to display.
Specify the data source component that identifies the dataset the data is found in.
Example
The following code specifies DataSource1 to be the DataSource of DBGrid1.
DBGrid1.DataSource := DataSource1;
See also
DataField property, SQL property
For queries
Declaration
property DataSource: TDataSource;
Set the DataSource property to the name of a TDataSource component in the application
to assign values to parameters not bound to values programmatically with Params or
ParamByName. If the unbound parameter names match any column names in the
specified data source, Delphi binds the current values of those fields to the
corresponding parameters. This capability enables applications to have linked queries.
Example
The LINKQRY sample application illustrates the use of the DataSource property to link a
query in a master-detail form. The form contains a TQuery component (named Orders)
with the following in its SQL property:
SELECT Orders.CustNo, Orders.OrderNo, Orders.SaleDate
FROM Orders
WHERE Orders.CustNo = :CustNo
The form also contains:
• A TDataSource named OrdersSource, linked to Orders by its DataSet property.
• A TTable component (named Cust).
See also
SQL property
DataType property
Applies to
TFieldDef, TParam objects; TBCDField, TBlobField, TBooleanField, TBytesField,
TCurrencyField, TDateField, TDateTimeField, TFloatField, TGraphicField, TIntegerField,
TMemoField, TSmallintField, TStringField, TTimeField, TVarBytesField, TWordField
components
Example
with Query1.Parameters do
for I := 0 to Count - 1 do
if Params[I].DataType = ftUnknown then
MessageDlg(‘Parameter ‘ + IntToStr(I) + ‘ is undefined’, mtWarning, [mbOK], 0);
Example
This example uses a label and a button on a form. When the user clicks the button, the
current date is displayed in the caption of the label:
procedure TForm1.Button1Click(Sender: TObject);
begin
Label1.Caption := 'Today is ' + DateToStr(Date);
end;
See also
DateToStr function, DayOfWeek function, DecodeDate procedure, Now function, Time
function
See also
TDateTime type
Example
This example uses a label and a button on a form. When the user clicks the button, the
current date is converted to a string and displayed as the caption of the label:
procedure TForm1.Button1Click(Sender: TObject);
begin
Label1.Caption := DateToStr(Date);
end;
See also
Date function, DateTimeToStr function, StrToDate function, TimeToStr function
change how the string is formatted by changing some of the date and time typed
constants.
Example
This example uses a label and a button on a form. When the user clicks the button, the
current date and time is converted to a string and displayed as the caption of the label:
procedure TForm1.Button1Click(Sender: TObject);
begin
Label1.Caption := DateTimeToStr(Now);
end;
See also
Date function, DateToStr function, Now function, StrToDate function, Time function,
TimeToStr function
Example
This example uses a button, an edit box, and a label on a form. When the user enters a
date in the edit box using the Month/Day/Year format, the caption of the label reports
the day of the week for the specified date.
procedure TForm1.Button1Click(Sender: TObject);
var
ADate: TDateTime;
begin
ADate := StrToDate(Edit1.Text);
Label1.Caption := 'Day ' + IntToStr(DayOfWeek(ADate)) + ' of the week';
end;
See also
Date function, EncodeDate function, Now function, StrToDate function, StrToDateTime
function
DBHandle property
Applies to
TTable, TQuery, TStoredProc components
DbiError procedure DB
Declaration
procedure DbiError(ErrorCode: Integer);
The DbiError procedure creates an error message by querying the Borland Database
Engine for the last error number and text and calls DatabaseError passing the result.
ErrorCode is used to obtain a text message from the engine if the error has already been
cleared.
DBLocale property
Applies to
TTable, TQuery, TStoredProc components
Declaration
property DBLocale: TLocale;
Run-time and read only. The DBLocale property allows you to make direct calls to the
Borland Database Engine using this specification of the language driver. Under most
circumstances you should not need to use this property, unless your application
requires some functionality not encapsulated in the VCL.
DDEConv property
Applies to
TDDEClientItem component
Declaration
property DdeConv: TDdeClientConv;
The DDEConv property specifies the DDE client conversation component to associate
with the DDE client item component. The value of DDEConv is the name of the DDE
client conversation component that defines the DDE conversation.
Example
The following code specifies DDEClientConv1 as the conversation of DDEClientItem1.
DDEClientItem1.DDEConv := DDEClientConv1.
See also
Name property
DDEItem property
Applies to
TDDEClientItem component
Declaration
property DDEItem: String;
The DDEItem property specifies the item of a DDE conversation. The value of DDEItem
depends on the linked DDE server application. DDEItem is typically a selectable portion
of text, such as a spreadsheet cell or a database field in an edit box. If the DDE server is a
Delphi application, DDEItem is the name of the linked DDE server component. For
example, to link to a DDE server component named DDEServer1, set DDEItem to
‘DDEServer1’.
See the documentation for the DDE server application for the specific information about
specifying DDEItem.
At design time, you can specify DDEItem either by typing the item string in the object
inspector or by pasting a link using the DDE Info dialog box, which appears if you click
the ellipsis (...) button for DDEService or DDETopic in the Object Inspector. After you
choose Paste Link in the DDE Info dialog box, you can choose the item from a list of
possible items for DDEItem in the object inspector if link information is still on the
Clipboard.
Example
The following code specifies a DDE item of ‘DDEServer1’.
DDEClientItem1.DDEItem := 'DDEServer1';
See also
DDEService property, DDETopic property
DDEService property
Applies to
TDDEClientConv component
Example
The following code specifies a DDE service of ‘Project1’.
DDEClientConv1.DDEService := 'Project1';
See also
DDEItem property, DDETopic property
DDETopic property
Applies to
TDDEClientConv component
Declaration
property DDETopic: string;
The DDETopic property specifies the topic of a DDE conversation. Typically, DDETopic
is a file name (and path, if necessary) used by the application specified in DDEService. If
the DDE server is an Delphi application, by default DDETopic is the caption of the form
containing the linked component. For example, to link to a component on a form named
Form1, set DDETopic to ‘Form1’. However, if the DDE client is linked to a
TDDEServerConv component, DDETopic is the name of the server conversation
component instead of the form caption. For example, to link to DDEServerConv1, set
DDETopic to ‘DDEServerConv1’.
See the documentation for the DDE server application for the specific information about
specifying DDETopic.
At design time, you can specify DDETopic either by typing the DDE server application
name in the object inspector or by choosing Paste Link in the DDE Info dialog box.
Example
The following code spGecifies a DDE topic of ‘Form1’.
DDEClientConv1.DDETopic := 'Form1';
See also
DDEItem property
Example
var
IntVar: Integer;
LongintVar: Longint;
begin
Intvar := 10;
LongintVar := 10;
Dec(IntVar); { IntVar := IntVar – 1 }
Dec(LongintVar, 5); { LongintVar := LongintVar – 5 }
end;
See also
Inc procedure, Pred function, Succ function
Example
This example uses a button and two labels on a form. When the user clicks the button,
the current date and time are reported in the captions of the two labels.
procedure TForm1.Button1Click(Sender: TObject);
See also
DecodeTime procedure
Example
This example uses a button and two labels on a form. When the user clicks the button,
the current date and time are reported in the captions of the two labels.
procedure TForm1.Button1Click(Sender: TObject);
var
Present: TDateTime;
Year, Month, Day, Hour, Min, Sec, MSec: Word;
begin
Present:= Now;
DecodeDate(Present, Year, Month, Day);
Label1.Caption := 'Today is Day ' + IntToStr(Day) + ' of Month '
+ IntToStr(Month) + ' of Year ' + IntToStr(Year);
DecodeTime(Present, Hour, Min, Sec, MSec);
Label2.Caption := 'The time is Minute ' + IntToStr(Min) + ' of Hour '
+ IntToStr(Hour);
end;
See also
DecodeDate procedure, EncodeTime function, Time function
Default property
Applies to
TBitBtn, TButton components
Declaration
property Default: Boolean;
The Default property indicates whether a push or bitmap button is the default button. If
Default is True, any time the user presses Enter, the OnClick event handler for that button
runs. The only exception to this is if the user selects another button before pressing Enter,
in which case the OnClick event handler for that button runs. Although your application
can have more than one button designated as a default button, the form calls the OnClick
event handler for the first button in the tab order.
Whenever any button has focus, it becomes the default button temporarily. When the
focus moves to a control that isn’t a button, the button with its Default property set to
True becomes the default button once again.
Example
This example makes the button named OK the default button:
procedure TForm1.FormCreate(Sender: TObject);
begin
OK.Default := True;
end;
See also
Cancel property
DefaultColWidth property
Applies to
TDrawGrid, TStringGrid components
Declaration
property DefaultColWidth: Integer;
The DefaultColWidth property determines the width of all the columns within the grid.
If you want to change the width of a single column within a grid without changing
other columns, use the ColWidths property during run time. If you change the
DefaultColWidth property value after changing the width of specified columns, all the
columns become the height specified in the DefaultColWidth property once again.
The default value is 64 pixels.
DefaultDrawing property
Applies to
TDBGrid, TDrawGrid, TStringGrid components
Declaration
property DefaultDrawing: Boolean;
The DefaultDrawing property determines if the cell is painted and the item it contains is
drawn automatically. If True, the default drawing occurs. If False, your application must
handle all the drawing details in the OnDrawCell event handler, or in the
OnDrawDataCell event handler for the data grid.
When DefaultDrawing is True, the Paint method initializes the Canvas’ font and brush to
the control font and the cell color. The cell is prepainted in the cell color and a focused
TRect object is drawn in the cell. The state of the cell is returned. The possible states are a
fixed cell, a focused cell, or a cell within the area the user has selected.
Example
The following code sets DefaultDrawing to False for DrawGrid1.
DrawGrid1.DefaultDrawing := False;
See also
OnDrawCell event, OnDrawDataCell event
DefaultExt property
Applies to
TOpenDialog, TSaveDialog components
Declaration
property DefaultExt: TFileExt;
The DefaultExt property specifies the extension that is added to the file name the user
types in the File Name edit box if the user doesn’t include a file-name extension in the
file name. If the user specifies an extension for the file name, the value of the DefaultExt
property is ignored. If the DefaultExt value remains blank, no extension is added to the
file name entered in the File Name edit box.
Legal property values include strings up to 3 characters in length. Don’t include the
period (.) that divides the file name and its extension.
Example
This example sets the default file extension to TXT, displays the Open dialog box, then
assigns the file name the user selects with the dialog box to a variable the application can
use to open a file:
procedure TForm1.Button1Click(Sender: TObject);
var
NameOfFile : TFileName;
begin
OpenDialog1.DefaultExt := ’TXT’;
if OpenDialog1.Execute then
NameOfFile := OpenDialog1.FileName;
end;
When this code runs, if the user types a file name in the File Name edit box in the Open
dialog box, but doesn’t specify an extension, the TXT extension is added to the file name,
and the entire file name is saved in the NameOfFile variable. For example, if the user
types MYNOTES as the file name, the string saved in the NameOfFile variable is
MYNOTES.TXT.
See also
FileName property, TOpenDialog component, TSaveDialog component
DefaultRowHeight property
Applies to
TDrawGrid, TStringGrid components
Declaration
property DefaultRowHeight: Integer;
The DefaultRowHeight property determines the height of all the rows within the grid.
The default value is 24 pixels.
If you want to change the height of a single row within a grid without changing other
rows, use the RowHeights property during run time. If you change the DefaultRowHeight
property value after changing the height of specified rows, all the rows become the
height specified in the DefaultRowHeight property once again.
Example
The following line of code changes the default height of the rows in a string grid control
to 10 pixels more than the original value:
Example
FileMenu in the following code is a menu that contains four menu items (menu
commands). They are New, Open, Save, and Save As, in that order. This event handler
deletes the Save command from the menu:
procedure TForm1.Button1Click(Sender: TObject);
begin
FileMenu.Delete(2);
end;
This example uses a list box and a button on a form. When the form appears, five items
are in the list box. When the user clicks the button, the second item in the list box is
deleted:
procedure TForm1.FormCreate(Sender: TObject);
var
I: Integer;
begin
for I := 1 to 5 do
ListBox1.Items.Add('Item ' + IntToStr(I));
end;
See also
Add method, Clear method, Insert method, Remove method
For outlines
Declaration
procedure Delete(Index: LongInt);
The Delete method removes the outline item with an Index property value equal to the
Index parameter from the list outline. If that item is has subitems, the subitems are also
deleted.
Outline items that appear after the deleted item are moved up and reindexed with valid
Index values. This is done automatically unless BeginUpdate has been called.
Example
The following code deletes the selected item from Outline1.
Outline1.Delete(Outline1.SelectedItem);
See also
Add method, AddChild method, Insert method
Example
var
s: string;
begin
s := 'Honest Abe Lincoln';
Delete(s,8,4);
Canvas.TextOut(10, 10, s); { 'Honest Lincoln' }
end;
See also
Concat function, Copy function, Insert procedure, Length function, Pos function
Example
The following code erases the file DELETE.ME in the current directory:
DeleteFile('DELETE.ME');
DeleteIndex method
Applies to
TTable component
Declaration
procedure DeleteIndex(const Name: string);
The DeleteIndex method deletes a secondary index for a TTable. Name is the name of the
index. You must have opened the table with exclusive access (Exclusive = True).
Example
Table1.DeleteIndex(‘NewIndex’);
See also
AddIndex method
DeleteTable method
Applies to
TTable component
Declaration
procedure DeleteTable;
The DeleteTable method deletes an existing database table. Before calling this method,
the DatabaseName, TableName and TableType properties must be assigned values. The
table must be closed.
Example
with Table1 do
begin
Active := False;
DatabaseName := ‘DBDEMOS’;
TableName := ‘Customer’;
TableType := ttParadox;
DeleteTable;
end;
DescriptionsAvailable method
Applies to
TStoredProc component
Declaration
function DescriptionsAvailable: Boolean;
The DescriptionsAvailable method indicates whether stored procedure parameter
information is available from the server. If the information is available, it returns True.
See also
Overload property, StoredProcName property
Destination property
Applies to
TBatchMove component
Declaration
property Destination: TTable;
Destination specifies a TTable component corresponding to the database table that will be
the destination of the batch move operation. The destination table may or may not
already exist.
Example
BatchMove1.Destination := Table1;
Destroy method
Applies to
All objects and components
Declaration
destructor Destroy;
The Destroy method destroys the object, component, or control and releases the memory
allocated to it.
You seldom need to call Destroy. Objects designed with Delphi create and destroy
themselves as needed, so you don’t have to worry about it. If you construct an object by
calling the Create method, you should call Free to release memory and dispose of the
object.
See also
Free method, Release method
Device property
Applies to
TFontDialog component
Declaration
property Device: TFontDialogDevice;
The Device property determines which device the returned font affects. These are the
possible values:
Value Meaning
fdScreen Affects the screen
fdPrinter Affects the printer
fdBoth Affects both the screen and the printer
Example
This example lets the user select a font to use for printing a file:
procedure TForm1.Button1Click(Sender: TObject);
var
FontName: TFont;
begin
FontDialog1.Device := fdPrinter;
FontDialog1.Execute;
FontName := FontDialog1.Font;
end;
See also
TFont object
DeviceID property
Applies to
TMediaPlayer component
Declaration
property DeviceID: Word;
Run-time and read only. The DeviceID property specifies the device ID for the currently
open multimedia device.
The value of DeviceID is determined when an device is opened with the Open method. If
+
no device is open, DeviceID is 0. +
Example
The following code opens MediaPlayer1 and displays the DeviceID in Edit1. If an
+
exception occurs, a message window displays the error number and string. D
procedure TForm1.BitBtn1Click(Sender: TObject);
var
MyErrorString: string;
begin
try
MediaPlayer1.Open;
Edit1.Text := IntToStr(MediaPlayer1.DeviceID);
except
MyErrorString := 'ErrorCode: ' + IntToStr(Error) + #13#10;
MessageDlg(MyErrorString + MediaPlayer1.ErrorMessage, mtError, [mbOk], 0);
end;
end;
DeviceType property
Applies to
TMediaPlayer component
Declaration
property DeviceType: TMPDeviceTypes;
The DeviceType property specifies a multimedia device type to open with the Open
method. The default is dtAutoSelect. The valid values for DeviceType are dtAutoSelect,
dtAVIVideo, dtCDAudio, dtDAT, dtDigitalVideo, dtMMMovie, dtOther, dtOverlay,
dtScanner, dtSequencer, dtVCR, dtVideodisc, or dtWaveAudio.
If DeviceType is dtAutoSelect, the device type is determined by the file extension specified
in the FileName property. If no device type is associated with the extension, you must
explicitly specify the correct device type by setting DeviceType to a value other than
dtAutoSelect.
A multimedia device is typically associated with an appropriate file-name extension
when you install the device. Associations are specified in the [mci extensions] section of
the Windows WIN.INI file. See the documentation for your specific device for
instructions about how to associate file-name extensions with the device.
Example
The following code checks to make sure that a filename is specified for MediaPlayer1 if
the DeviceType is set to dtAutoSelect before opening the device.
procedure TForm1.FormCreate(Sender: TObject);
begin
with MediaPlayer1 do
if (DeviceType = dtAutoSelect) and (FileName = '') then
MessageDlg('You must specify a filename for the MediaPlayer', mtError, [mbOk], 0)
else
Open;
end;
Directory property
Applies to
TDirectoryListBox, TFileListBox components
Declaration
property Directory: string;
The value of the Directory property determines the current directory for the file list box
and directory list box components. The file list box displays the files in the directory
specified in the Directory property. The directory list box displays the value of the
Directory property as the current directory in the list box.
Examine the example to see how a directory list box and a file list box can work together
through their Directory properties.
Example
If you have a file list box and a directory list box on a form, this code changes the current
directory in the directory list box and displays the files in that directory in the file list
box when the user changes directories using the directory list box:
procedure TForm1.DirectoryListBox1Change(Sender: TObject);
begin
FileListBox1.Directory := DirectoryListBox1.Directory;
end;
See also
DirLabel property, Drive property, FileList property
If only a directory name is entered as the value of Name, DirectoryExists searches for the
+
directory within the current directory. If a full path name is entered, DirectoryExists
searches for the directory along the designated path.
+
Example
+
This example uses an edit box, a label, and a button on a form. When the user enters a
directory name in the edit box and clicks the button, whether or not the directory exists
D
is reported in the caption of the label:
procedure TForm1.Button1Click(Sender: TObject);
begin
if DirectoryExists(Edit1.Text) then
Label1.Caption := Edit1.Text + ' exists'
else
Label1.Caption := Edit1.Text + ' does not exist';
end;
See also
ForceDirectories procedure, SelectDirectory function
DirLabel property
Applies to
TDirectoryListBox component
Declaration
property DirLabel: TLabel;
The DirLabel property provides a simple way to display the current directory as the
caption of a label control. When the current directory changes in the directory list box,
the change is reflected in the caption of the label.
Specify the label you want updated with the current directory as the value of the
DirLabel property.
Example
This example uses a button, an edit box, a label, a drive combo box, a directory list box, a
file list box, and a filter combo box on a form. When the user clicks the button, the rest of
the controls of the form begin working together like the controls in an Open or Save
dialog box.
procedure TForm1.Button1Click(Sender: TObject);
begin
DriveComboBox1.DirList := DirectoryListBox1;
DirectoryListBox1.FileList := FileListBox1;
DirectoryListBox1.DirLabel := Label1;
FileListBox1.FileEdit := Edit1;
FilterComboBox1.FileList := FileListBox1;
end;
See also
Caption property, Directory property, DirList property, FileEdit property, FileList
property
DirList property
Applies to
TDriveComboBox component
Declaration
property DirList: TDirectoryListBox;
The DirList property provides a simple way to connect a drive combo box with a
directory list box. When a new drive is selected in the drive combo box, the specified
directory list box updates to display the directory structure and the current directory on
the new drive.
Specify the directory list box you want updated as the value of DirList.
Example
This example uses a button, an edit box, a label, a drive combo box, a directory list box, a
file list box, and a filter combo box on a form. When the user clicks the button, the rest of
the controls of the form begin working together as the controls in an open or save dialog
box do.
procedure TForm1.Button1Click(Sender: TObject);
begin
DriveComboBox1.DirList := DirectoryListBox1;
DirectoryListBox1.FileList := FileListBox1;
DirectoryListBox1.DirLabel := Label1;
FileListBox1.FileEdit := Edit1;
FilterComboBox1.FileList := FileListBox1;
end;
See also
Directory property, DirLabel property, Drive property, FileEdit property, FileList property
DisableControls method
Applies to
TTable, TQuery, TStoredProc components
Declaration
procedure DisableControls;
The DisableControls method temporarily disconnects the dataset from all TDataSource
+
components. While the data sources are disconnected, associated data-aware controls
will not reflect changes to datasets. When iterating over a dataset with Next or Prior
+
methods, calling DisableControls first will speed the process, eliminating the need to
update the screen each time.
+
Use EnableControls to restore the connection. The dataset maintains a count of the
number of calls to DisableControls and EnableControls, so only the last call to
D
EnableControls will actually update the data sources.
Example
with Table1 do
begin
DisableControls;
{ Move forward five records }
try
for I := 1 to 5 do Next;
finally
{ Update the controls to the current record }
EnableControls;
end;
Example
var
S: string;
begin
S := IntToStr(DiskFree(0) div 1024) + ' Kbytes free.';
Canvas.TextOut(10, 10, S);
end;
See also
DiskSize function
Example
var
S: string;
begin
S := IntToStr(DiskSize(0) div 1024) + ' Kbytes capacity.';
Canvas.TextOut(10, 10, S);
end;
See also
DiskFree function
Display property
Applies to
TMediaPlayer component
Declaration
property Display: TWinControl;
The Display property specifies the display window for an multimedia device that uses a
window for output. Assign the name of a windowed control such as a form or panel to
Display to display output in that control.
The default value of Display is nil. If the value of Display is nil, the device creates its own
window to display output. Also, if you Free the control assigned to Display after the
device has been opened, video output will be in its own default window.
Examples of multimedia devices that use a window to display output are Animation,
AVI Video, Digital Video, Overlay, and VCR.
Example
The following example displays the .AVI video file 'FOOTBALL.AVI' in the client area
of Form2.
procedure TForm1.BitBtn1Click(Sender: TObject);
begin
with MediaPlayer1 do begin
try
FileName := 'football.avi';
See also
Capabilities property, DeviceType property, DisplayRect property, Open method
DisplayFormat property
Applies to
TDateField, TDateTimeField, TIntegerField, TSmallintField, TTimeField, TWordField
components
Declaration
property DisplayFormat: string
The DisplayFormat property is used to format the value of the field for display purposes.
For TIntegerField, TSmallintField, and TWordField, formatting is performed by
FloatToTextFmt. If DisplayFormat is not assigned a string, the value is formatted by Str.
For TDateField, TDateTimeField, and TTimeField, formatting is performed by
DateTimeToStr. If DisplayFormat is not assigned a string, the value is formatted according
to the default Windows specifications in the [International] section of the WIN.INI file.
For TBCDField, TCurrencyField, and TFloatField, formatting is performed by
FloatToTextFmt. If DisplayFormat is not assigned a string, the value is formatted
according to the value of the Currency property.
See also
FmtStr procedure, Format function, FormatBuf function, FormatDateTime function,
FormatFloat function, StrFmt function, StrLFmt function
DisplayLabel property
Applies to
TBCDField, TBlobField, TBooleanField, TBytesField, TCurrencyField, TDateField,
TDateTimeField, TFloatField, TGraphicField, TIntegerField, TMemoField, TSmallintField,
TStringField, TTimeField, TVarBytesField, TWordField components
Declaration
property DisplayLabel: string;
DisplayLabel contains the column heading for a field displayed by a TDBGrid
component. If DisplayLabel is null, the FieldName property is used to supply the column
heading.
DisplayName property
Applies to
TBCDField, TBlobField, TBooleanField, TBytesField, TCurrencyField, TDateField,
TDateTimeField, TFloatField, TGraphicField, TIntegerField, TMemoField, TSmallintField,
TStringField, TTimeField, TVarBytesField, TWordField components
Declaration
property DisplayName: Pstring;
Run-time and read only. DisplayName returns the name of the field for display purposes.
Use DisplayName in your code to use the same algorithm that other Delphi components
use when they need the DisplayLabel or FieldName of a field.
DisplayRect property
Applies to
TMediaPlayer component
Declaration
property DisplayRect: TRect;
Run-time only. The DisplayRect property specifies the rectangle area within the form
specified in the Display property used to display output from a multimedia device.
DisplayRect is ignored if Display is nil.
Assign a TRect record to DisplayRect to display output in a specific rectangle area on a
form. The Rect function can be used to create a TRect record.
Examples of multimedia devices that use a window to display output are Animation,
AVI Video, Digital Video, Overlay, and VCR.
Media that use a rectangle to display output usually perform best if the default
DisplayRect size is used. To set DisplayRect to the default size, use 0, 0 for the lower right
corner. Position the rectangle with the upper left corner.
Note You must set DisplayRect after the media device is opened.
DisplayText property
Applies to
TBCDField, TBlobField, TBooleanField, TBytesField, TCurrencyField, TDateField,
TDateTimeField, TFloatField, TGraphicField, TIntegerField, TMemoField, TSmallintField,
TStringField, TTimeField, TVarBytesField, TWordField components
Declaration
property DisplayText: string;
Run-time and read only. The string value for the field when it is displayed in a data-
aware control that is not in Edit mode. Data-aware controls such as TDBEdit rely on
DisplayText to provide the formatting for each field.
The default string depends on a field’s data type. You can control the strings returned
by DisplayText by specifying a DisplayFormat string or by providing an OnGetText event
handler.
For a TStringField, the contents of the field is formatted using the EditMask property.
For a TIntegerField, TSmallintField, or TWordField, if DisplayFormat has been assigned a
value, FloatToTextFmt is called with it; otherwise Str is called.
For a TFloatField or TBCDField, FloatToTextFmt is called with the DisplayFormat property.
For a TCurrencyField, if DisplayFormat has been assigned a value, FloatToTextFmt is called
with it; otherwise, FloatToTextFmt is called with the ffCurrency flag and CurrencyDecimals
variable.
For a TDateTimeField, DateTimeToStr is called with the DisplayFormat property. For a
TDateField, DateTimeToStr is called with the DisplayFormat property, except that the
ShortDateFormat variable will be substituted if DisplayFormat is unassigned. For a
TTimeField, DateTimeToStr is called with the DisplayFormat property, except that the
LongTimeFormat variable will be substituted if DisplayFormat is unassigned.
Example
{ Display a message that the current value is invalid }
MessageDlg(Field1.DisplayText + ‘ is invalid’, mtWarning, [mbOK], 0);
DisplayValue property
Applies to
TDBLookupCombo, TDBLookupList components
Declaration
property DisplayValue : string;
Run-time only. The DisplayValue is the string that appears in the database lookup combo
box or database lookup list box. Its value is contained in the field specified as the
LookupDisplay field. The current value of the Value property, which determines the
current record in the lookup table, also determines which string is the DisplayValue
string.
Example
The following code makes the caption of a button equal to the DisplayValue of
DBLookupCombo1.
Button1.Caption := DBLookupCombo1.DisplayValue;
See also
LookupField property
DisplayValues property
Applies to
TBooleanField component
Declaration
property DisplayValues: string;
DisplayValues controls the manner in which the TBooleanField is translated to and from
display format. Set DisplayValues to ‘T;F’ to use ‘T’ and ‘F’ for values of True and False.
You can use any pair of phrases you want, separated by a semicolon. If one phrase is
omitted, no text is displayed and a data-aware control with no text assigns the
corresponding value to the field. The default value is ‘True;False’.
Example
Field1.DisplayValues := 'Yes;No';
Field2.DisplayValues := 'Oui;Non';
See also
DisplayLabel property, DisplayText property
Example
type
Str18 = string[18];
var
P: ^Str18;
begin
New(P);
P^ := 'Now you see it...';
Dispose(P); { Now you don't... }
end;
See also
FreeMem procedure, GetMem procedure, New procedure
Example
The following code allocates and frees heap space for a copy of string S pointed to by P,
then deallocates the heap space pointed to by P:
var
P: PString;
S: string;
begin
S := 'Ask me about Blaise';
P := NewStr(S);
DisposeStr(P):
end;
See also
NewStr function
DitherBackground property
Applies to
TTabSet component
Declaration
property DitherBackground: Boolean;
The DitherBackground property determines whether the selected background color set
with the BackgroundColor property is dithered. Dithering means the background is
lightened by 50%, which is intended to make the tabs easier to see. If DitherBackground is
True, the tab set control background is dithered. If it is False, there is no dithering.
The default value is True.
Example
This event handler toggles the dithering of the tab set control’s background each time
the user clicks the form:
procedure TForm1.FormClick(Sender: TObject);
begin
if TabSet1.DitherBackground = True then
TabSet1.DitherBackground := False
Down property
Applies to
TSpeedButton component
Declaration
property Down: Boolean;
The Down property of a speed button determines if the button appears in an up
(unselected) or down (selected) state. Speed buttons are initially in their up (unselected)
state. This occurs because the default setting of the Down property is False.
To initially display a speed button in its down state, set the Down property to True. For
example, if you use a panel component with several speed buttons to create a tools
palette, you might want one of the speed buttons selected when the palette first appears.
Although you can use a group of speed buttons with the AllowAllUp property set to
False to make the tool palette buttons work as a group, you must set the Down property
for the button you want to be selected initially. You can also use the Down property at
run time any time you want to put a button in a down state without the user clicking it
first.
Example
This code displays the speed button in a down state:
SpeedButton1.Down := True;
See also
AllowAllUp property, GroupIndex property
DragCursor property
Applies to
TBitBtn, TButton, TCheckBox, TComboBox, TDBCheckBox, TDBEdit, TDBGrid, TDBImage,
TDBListBox, TDBLookupCombo, TDBLookupList, TDBMemo, TDBNavigator,
TDBRadioGroup, TDBText, TDirectoryListBox, TDriveComboBox, TEdit, TFileListBox,
TFilterComboBox, TGroupBox, TImage, TLabel, TListBox, TMaskEdit, TMemo, TOutline,
TPaintBox, TPanel, TRadioButton, TScrollBar, TScrollBox, TShape, TNotebook controls
Declaration
property DragCursor: TCursor;
The DragCursor property determines the shape of the mouse pointer when the pointer is
over a component that will accept an object being dragged. These are the possible
images:
Example
The following code changes the DragCursor of Memo1 to crIBeam.
Memo1.DragCursor := crIBeam;
See also
BeginDrag method, Cursor property, Cursors property, Dragging method, EndDrag
method, OnDragDrop event, OnDragOver event, OnEndDrag event
Dragging method
Applies to
All controls
See also
BeginDrag method, DragMode property, EndDrag method, OnDragDrop event,
OnDragOver event, TDragState type
DragMode property
Applies to
TBitBtn, TButton, TCheckBox, TComboBox, TDBCheckBox, TDBComboBox, TDBEdit,
TDBGrid, TDBImage, TDBText, TDBListBox, TDBLookupCombo, TDBLookupList,
TDBMemo, TDBNavigator, TDBRadioGroup, TDirectoryListBox, TDrawGrid,
TDriveComboBox, TEdit, TFileListBox, TFilterComboBox, TGroupBox, TImage, TLabel,
TListBox, TMaskEdit, TMemo, TOLEContainer, TOutline, TPaintBox, TRadioButton,
TScrollBar, TScrollBox, TShape, TStringGrid, TNotebook controls
Declaration
property DragMode: TDragMode;
The DragMode property determines the drag and drop behavior of a control. These are
the possible values:
Value Meaning
dmAutomatic If dmAutomatic is selected, the control is ready to be dragged; the user just
clicks and drags it.
dmManual If dmManual is selected, the control can’t be dragged until the application calls
the BeginDrag method.
If a control’s DragMode property value is dmAutomatic, the application can disable the
drag and drop capability at run time by changing the DragMode property value to
dmManual.
Example
This example determines whether the drag mode of the button on the form is manual. If
it is, the dragging the button becomes possible.
procedure TForm1.Button1Click(Sender: TObject);
begin
if Button1.DragMode = dmManual then
Button1.BeginDrag(True);
end;
See also
BeginDrag method, EndDrag method
Draw method
Applies to
TCanvas object
Declaration
procedure Draw(X, Y: Integer; Graphic: TGraphic);
The Draw method draws the graphic specified by the Graphic parameter on the canvas at
the location given in the screen pixel coordinates (X, Y). Graphics can be bitmaps, icons,
or metafiles.
Example
The following code draws the graphic in C:\WINDOWS\TARTAN.BMP centered in
Form1 when the user clicks Button1. Attach this code to the OnClick event handler of
Button1.
procedure TForm1.Button1Click(Sender: TObject);
var
Bitmap1: TBitmap;
begin
Bitmap1 := TBitmap.Create;
Declaration
procedure DrawFocusRect(const Rect: TRect);
The DrawFocusRect method draws a rectangle in the style used to indicate that the
rectangle has the focus. Because this is an XOR function, calling it a second time and
specifying the same rectangle removes the rectangle from the screen.
The rectangle this function draws cannot be scrolled. To scroll an area containing a
rectangle drawn by this function, call DrawFocusRect to remove the rectangle from the
screen, scroll the area, and then call DrawFocusRect to draw the rectangle in the new
position.
Example
This examples uses a radio button and a button on a form. When the user clicks the
button, the code draws a rectangle around the radio button.
procedure TForm1.Button1Click(Sender: TObject);
var
NewRect: TRect;
begin
NewRect := RadioButton1.BoundsRect;
with NewRect do
begin
Left := Left - 10;
Top := Top - 10;
Right := Right + 10;
Bottom := Bottom + 10;
end;
Form1.Canvas.DrawFocusRect(NewRect);
end;
See also
Arc method, Chord method, Ellipse method, FrameRect method, Pie method, Rectangle
method
Drive property
Applies to
TDirectoryListBox, TDriveComboBox, TFileListBox components
Declaration
property Drive: Char;
Run-time only. For the drive combo box, the Drive property determines which drive is
displayed in the edit control of the combo box. When the user uses the drive combo box
to select a new drive, the selected drive becomes the value of the Drive property. The
value of the Text property also changes to the new volume name when the Drive
property value changes.
For the directory list box, the Drive property determines which drive the list box
displays the directory structure on. When the value of Drive changes, the Directory value
changes also to the current directory on the specified drive.
For the file list box, the Drive property determines which drive the list box displayed the
files on. When the value of Drive changes, the Directory value also changes to the current
directory on the specified drive.
Example
The following example assumes that a drive combo box, a file list box, and a directory
list box are on a form. This code changes the drive displayed in the drive combo box,
displays the current directory of the selected drive in the directory list box, and displays
the files in the current directory of the selected drive in the file list box when the user
selects a drive in the drive combo box:
procedure TForm1.DriveComboBox1Change(Sender: TObject);
begin
DirectoryListBox1.Drive := DriveComboBox1.Drive;
FileListBox1.Directory := DirectoryListBox1.Directory;
end;
See also
Directory property, DirList property, Text property
DriverName property
Applies to
TDataBase component
Declaration
property DriverName: TSymbolStr;
DriverName is the name of a BDE driver, such as STANDARD (for dBASE and Paradox),
+
ORACLE, SYBASE, INFORMIX or INTERBASE. This property will be cleared if
AliasName is set, because an AliasName specifies a driver type. Conversely, setting this
+
property will clear AliasName. +
If you try to set DriverName of a TDatabase for which Connected is True, Delphi will raise
an exception. D
Example
Database1.DriverName := ‘STANDARD’;
DropConnections method
Applies to
TSession component
Declaration
procedure DropConnections;
The DropConnections method drops all inactive database connections. By default,
temporary database components keep their connections to the server open even when
not in use so that they do not have to log in to the server each time a dataset component
is opened.
Example
Session.DropConnections;
See also
Session variable, Temporary property
DropDown method
Applies to
TDBLookupCombo component
Declaration
procedure DropDown;
The DropDown method opens or “drops down” the database lookup combo box so that
the user has a list of values to choose from.
See also
CloseUp method
DropDownCount property
Applies to
TComboBox, TDBComboBox, TDBLookupCombo components
Declaration
property DropDownCount: Integer;
The DropDownCount property determines how long the drop-down list of a combo box
is. By default, the drop-down list is long enough to contain eight items without
requiring the user to scroll to see them all. If you would like the drop-down list to be
smaller or larger, specify a number larger or smaller than eight as the DropDownCount
value.
If the DropDownCount value is larger than the number of items in the drop-down list, the
drop-down list is just large enough to hold all the items and no larger. For example, if
the list contains three items, the drop-down list is only long enough to display the three
items, even if the DropDownCount is eight.
Example
The following code assigns three to the DropDownCount property of ComboBox1. To see
more than three items in the drop-down list, the user must scroll.
ComboBox1.DropDownCount := 3;
See also
DropDownWidth property
DropDownWidth property
Applies to
TDBLookupCombo component
Declaration
property DropDownWidth: Integer;
The DropDownWidth property determines how wide the drop-down list of the combo
box is in pixels. The default value is 0, which means the drop-down list is the same
width as the combo box.
The DropDownWidth property is useful when you are displaying multiple fields, and
therefore, multiple columns in the database lookup combo box.
Example
This code displays three fields in the drop-down list of the database lookup combo box.
Each column has a title and is separated from the other columns by a line. The combo
box displays ten items at a time; therefore, the user must scroll to view the rest of the
+
items. The drop-down list is 600 pixels wide so all the fields fit in the drop-down list. +
procedure TForm1.FormCreate(Sender: TObject);
begin
DBLookupCombo1.LookupDisplay := 'Company;City;Country';
+
DBLookupCombo1.Options := [loColLines,loTitles];
DBLookupCombo1.DropDownCount := 10;
D
DBLookupCombo1.DropDownWidth := 600;
end;
See also
DropDownCount property, LookupDisplay property, Options property
DroppedDown property
Applies to
TComboBox, TDBComboBox components
Declaration
property DroppedDown: Boolean;
Run-time only. The DroppedDown property determines whether the drop-down list of
the combo box is open or closed. If DroppedDown is True, the drop-down list is visible. If
DroppedDown is False, the drop-down list is closed. The default value is False.
See also
DropDownCount property
dsEditModes const
Declaration
dsEditModes = [dsEdit, dsInsert, dsSetKey];
dsEditModes is the subset of TDataSetState elements which the State property of a dataset
component will have if the current record of the dataset is being modified. It is also uses
by the UpdateRecord of a dataset component.
Example
function MakeHexWord(w: Word): string;
const
hexChars: array [0..$F] of Char = '0123456789ABCDEF';
var
HexStr : string;
begin
HexStr := '';
HexStr := HexStr + hexChars[Hi(w) shr 4];
HexStr := HexStr + hexChars[Hi(w) and $F];
HexStr := HexStr + hexChars[Lo(w) shr 4];
HexStr := HexStr + hexChars[Lo(w) and $F];
MakeHexWord := HexStr;
end;
procedure TForm1.Button1Click(Sender: TObject);
var
i: Integer;
Y: Integer;
S: string;
begin
Y := 10;
S := 'The current code segment is $' + MakeHexWord(CSeg);
Canvas.TextOut(5, Y, S);
Y := Y + Canvas.TextHeight(S) + 5;
S := 'The global data segment is $' + MakeHexWord(DSeg);
Canvas.TextOut(5, Y, S);
Y := Y + Canvas.TextHeight(S) + 5;
S := 'The stack segment is $' + MakeHexWord(SSeg);
Canvas.TextOut(5, Y, S);
Y := Y + Canvas.TextHeight(S) + 5;
S := 'The stack pointer is at $' + MakeHexWord(SPtr);
Canvas.TextOut(5, Y, S);
Y := Y + Canvas.TextHeight(S) + 5;
S := 'i is at offset $' + MakeHexWord(Ofs(i));
Canvas.TextOut(5, Y, S);
Y := Y + Canvas.TextHeight(S) + 5;
S := 'in segment $' + MakeHexWord(Seg(i));
Canvas.TextOut(5, Y, S);
end;
See also
CSeg function, SSeg function
Value Meaning
dupIgnore Attempts to add a duplicate string to a sorted string list are ignored
dupAccept Duplicate strings can be added to a sorted string list
dupError Adding a duplicate string results in an EListError exception
Example
The following code makes StringList1 ignore duplicate entries.
StringList1.Duplicates := dupIgnore;
See also
Sort method, Sorted property
EDBEngineError object DB
EDBEngineError = class(EDatabaseError)
private
FErrors: TList;
function GetError(Index: Integer): TDBError;
function GetErrorCount: Integer;
public
constructor Create(ErrorCode: DBIResult);
destructor Destroy;
property ErrorCount: Integer;
property Errors[Index: Integer]: TDBError;
end;
Description
The EDBEngineError exception is raised whenever a BDE error occurs. The exception
contains two public properties of significance:
The objects contained in the Errors property are of type TDBError, which is declared like
this:
TDBError = class
private
FErrorCode: DBIResult;
FNativeError: Longint;
FMessage: TMessageStr;
function GetCategory: Byte;
function GetSubCode: Byte;
public
constructor Create(Owner: EDBEngineError; ErrorCode: DBIResult;
NativeError: Longint; Message: PChar);
property Category: Byte;
property ErrorCode: DBIResult;
property SubCode: Byte;
property Message: TMessageStr;
property NativeError: Longint;
end;
These are the public properties of the TDBError object:
Example
Table1.Edit;
See also
AutoEdit property
See also
DataSet property, Insert method
EditFormat property
Applies to
TIntegerField, TSmallintField, TWordField components
Declaration
property EditFormat: string;
EditFormat is used to format the value of the field for editing purposes.
For TIntegerField, TSmallintField, and TWordField, formatting is performed by
FloatToTextFmt. If EditFormat is not assigned a string, but DisplayFormat does have a
value, the DisplayFormat string is used. Otherwise, the value is formatted by to the
shortest possible string.
For TBCDField, TCurrencyField, and TFloatField, formatting is performed by
FloatToTextFmt. If EditFormat is not assigned a string but DisplayFormat does have a
value, the DisplayFormat string will be used. Otherwise, the value is formatted according
to the value of the Currency property.
EditKey method
Applies to
TTable component
Declaration
procedure EditKey;
Use the EditKey method to modify the contents of the search key buffer. This method is
useful only when searching on multiple fields after calling SetKey. Call GotoKey to move
the cursor to the record with the corresponding key.
EditKey differs from SetKey in that the latter clears all the elements of the search key
buffer to the default values (or NULL). EditKey leaves the elements of the search key
buffer with their current values.
Example
with Table1 do
begin
EditKey;
FieldByName(‘State’).AsString := ‘CA‘;
FieldByName(‘City’).AsString := ‘Santa Barbara‘;
GotoKey;
end;
See also
IndexFields property
These characters (already mentioned in previous table) are typed constants declared in
the Mask unit whose value you can change at run time, although the need for this should
be limited:
Example
This example assigns an edit mask to the masked edit box on the form. The edit mask
makes it easy to enter American telephone numbers in the edit box.
procedure TForm1.FormCreate(Sender: TObject);
begin
MaskEdit1.EditMask := '!\(999\)000-0000;1;
MaskEdit1.Text := '';
MaskEdit1.AutoSelect := False;
end;
See also
OnGetEditMask event, EditText property, Text property
Example
Field1.EditMask := Field2.EditMaskPtr^;
EditorMode property
Applies to
TDBGrid, TDrawGrid, TStringGrid components
Declaration
property EditorMode: Boolean;
Run-time only. The EditorMode property determines whether the grid is in automatic
Edit mode. When the grid is in automatic edit mode, the user can type in a cell without
having to press Enter or F2 first. If the Options property set includes the value
goAlwaysShowEditor (goAlwaysShowEditor is True), the grid is in automatic edit mode,
just as if EditorMode is True. While you are most likely to set the Options property values
at design time, the EditorMode property makes it easy to control when editing is
permitted at run time.
If EditorMode is True, the grid is in automatic edit mode as long as the Options property
set includes the value goEditing (or dgEditing for the data grid). If goEditing or dgEditing is
not in the Options set (goEditing or dgEditing is False), setting EditorMode to True has no
effect, and the user cannot edit the contents of a cell.
If EditorMode is False and the Options property set includes the value goEditing or
dgEditing, but not the value goAlwaysShowEditor (or dgAlwaysShowEditor for the data
grid), the user can enter edit mode by pressing either Enter or F2 before editing the
contents of each cell.
Example
The following code sets EditorMode to True for StringGrid1.
StringGrid1.EditorMode := True;
See also
Options property
EditRangeEnd method
Applies to
TTable component
Declaration
procedure EditRangeEnd;
EditRangeEnd enables you to modify the beginning range of the dataset filter established
with SetRangeEnd. Subsequent assignments to field values will modify the values of the
ending field range previously set with SetRangeEnd. Call ApplyRange to apply the new
range and filter the dataset.
EditRangeEnd differs from SetRangeEnd in that the latter clears all the elements of the
search key buffer to the default values (NULL). EditRangeEnd leaves the elements of
search key buffer with their current values.
Note With Paradox or dBASE tables, these methods work only with indexed fields. With SQL
databases, they can work with any columns specified in the IndexFieldNames property.
Example
{ Limit the range from ‘Goleta’ to ‘Santa Barbara’}
with Table1 do
begin
EditRangeStart; { Set the beginning key }
FieldByName(‘City’).AsString := ‘Goleta‘;
EditRangeEnd; { Set the ending key }
FieldByName(‘City’).AsString := ‘Santa Barbara‘;
ApplyRange; { Tell the dataset to establish the range }
end;
See also
KeyExclusive property, KeyFieldCount property
EditRangeStart method
Applies to
TTable component
Declaration
procedure EditRangeStart;
EditRangeStart enables you to modify the lower key limit established with SetRangeStart.
+
Call ApplyRange to apply the new range and filter the dataset. +
EditRangeStart differs from SetRangeStart in that the latter clears all the elements of the
search key buffer to the default values (NULL). EditRangeStart leaves the elements of the +
search key buffer with their current values.
Note With Paradox or dBASE tables, these methods work only with indexed fields. With SQL +
databases, they can work with any columns specified in the IndexFieldNames property.
E
Example
{ Limit the range from ‘Goleta’ to ‘Santa Barbara’}
with Table1 do
begin
EditRangeStart; { Set the beginning key }
FieldByName(‘City’).AsString := ‘Goleta‘;
EditRangeEnd; { Set the ending key }
FieldByName(‘City’).AsString := ‘Santa Barbara‘;
ApplyRange; { Tell the dataset to establish the range }
end;
See also
KeyExclusive property, EditRangeEnd method, SetRange method, SetRangeEnd method
EditText property
Applies to
TDBEdit, TMaskEdit components
Declaration
property EditText: string;
Run-time only. The EditText property is the value of the Text property as it appears in
the edit box at run time with the mask specified in the EditMask property applied. If
literal mask characters are not saved and no character is substituted for blanks, the
values of EditText and Text are the same.
EditText is what the user actually sees in the edit box at run time.
See also
EditMask property, Text property
The EDivByZero exception is an integer math exception. The exception occurs when
your application attempts to divide an integer type by zero. For example, this code
raises an EDivByZero exception:
var
X, Y: Integer;
begin
X := 0;
Y := 10;
Y := Y div X;
end;
Exception Meaning
EGPFault A general protect fault, which is usually caused by an uninitialized pointer or object.
EStackFault Illegal access to the processor’s stack segment.
EPageFault The Windows memory manager was unable to correctly use the Windows swap file.
EInvalidOpCode The processor encountered an undefined instruction. Usually this means the
processor was trying to execute data or uninitialized memory.
The EFilerError is raised when an attempt is made to register the same class twice. It is
+
also the parent of these exceptions that occur when reading or writing streams: +
Exception
EReadError
Description
The ReadBuf method cannot read the specified number of bytes
+
EWriteError
EClassNotFound
The WriteBuf method cannot write the specified number of bytes
A component on the form has been deleted from the form type declaration
+
E
EFOpenError object Classes
Declaration
EFOpenError = class(EStreamError);
The EFOpenError exception is raised when an attempt is made to create a file stream
object and the specified file cannot be opened.
The $I+ directive must be in effect or input/output errors will not raise an exception. If
an I/O error occurs when your application is in the $I- state, your application must call
the IOResult function to clear the error.
Description
The EIntError exception is a generic integer math exception. Although it is never raised
in the run-time library, it is the base from which other integer math exceptions descend.
These are the integer math exceptions:
Exception Meaning
EDivByZero An attempt was made to divide by zero
ERangeError Number or expression out of range
EIntOverflow Integer operation overflowed
Description
The EIntOverFlow exception is an integer math exception. It occurs when a calculated
result is too large to fit within the register allocated for it and therefore, data is lost. For
example, this code results in an overflow condition as the calculation result overflows a
register:
var
SmallNumber: Shortint;
X, Y: Integer;
begin
X := 127;
Y := 127;
SmallNumber := X * Y * 100;
end;
The EIntOverFlow occurs only if range checking is turned on (your code includes the
$O+ directive or you set the Overflow-checking option using the Options|Project dialog
box).
See also the ERangeError exception.
Description
An EInvalidGraphicOperation is raised when an illegal operation is attempted on a
graphic. For example, if your application attempts to resize an icon, the invalid graphic
operation is raised:
var
AnIcon: TIcon;
begin
AnIcon := TIcon.Create;
AnIcon.LoadFromFile('C:\WINDOWS\DIRECTRY.ICO');
AnIcon.Width := 100; { an invalid graphic operation exception is raised }
...
Eject method
Applies to
TMediaPlayer component
Declaration
procedure Eject;
The Eject method ejects the loaded medium from the open multimedia device. Eject is
called when the Eject button on the media player control is clicked at run time.
Upon completion, Eject stores a numerical error code in the Error property, and the
corresponding error message in the ErrorMessage property.
The Wait property determines whether control is returned to the application before the
Eject method has been completed. The Notify property determines whether Eject
generates an OnNotify event.
Example
This code ejects the CD from the CD-ROM player after 10 seconds. For the code to run
correctly, you must have your CD audio device installed correctly, and the device must
have software ejecting capabilities.
var
TimerOver: Word;
See also
Capabilities property
A list error exception is raised when you insert a string into a sorted string list, as the
+
string you insert at the specified position may put the string list out of sorted order. For
example, this code raises the list error exception:
+
procedure TForm1.FormCreate(Sender: TObject);
var
+
I: Integer;
begin
+
for I := 1 to 5 do
ListBox1.Items.Add('Item ' + IntToStr(I)); E
end;
procedure TForm1.Button1Click(Sender: TObject);
begin
try
ListBox1.Items.Insert(0, 'Try to insert here');
except
on EListError do
MessageDlg(‘Attempt to insert into a sorted list’, mtWarning, [mbOK], 0);
end;
end;
Ellipse method
Applies to
TCanvas object
Declaration
procedure Ellipse(X1, Y1, X2, Y2: Integer);
The Ellipse method draws an ellipse defined by a bounding rectangle on the canvas. The
top left point of the bounding rectangle is at pixel coordinates (X1, Y1) and the bottom
right point is at (X2, Y2). If the points of the rectangle form a square, a circle is drawn.
Example
The following code draws an ellipse filling the background of a form:
procedure TForm1.FormPaint(Sender: TObject);
begin
Canvas.Ellipse(0, 0, ClientWidth, ClientHeight);
end;
See also
Arc method, Chord method, Draw method, DrawFocusRect method, Pie method,
StretchDraw method
Exception Meaning
EInvalidOp Processor encountered an undefined instruction
EZeroDivide Attempt to divide by zero
EOverflow Floating-point operation overflowed
EUnderflow Floating-point operation underflowed
Description
The EMCIDeviceError exception is raised if an error occurs when accessing a multimedia
device. The most common cause for the exception is trying to access a multimedia
device before it has been opened with the Open method.
The Button argument can be one of the following values: btBack, btEject, btNext, btPause,
+
btPlay, btPrev, btRecord, btStep, or btStop. +
The default value of the DoDefault argument is True. If DoDefault is True, the media
player control calls the method that corresponds to the clicked button. For example, if +
the user clicks the Play button (btPlay), the Play method is called.
If DoDefault is False, you must supply the code that executes when a media player +
control button is clicked in the OnClick event handler. The following table lists the
default methods corresponding to the media player control buttons: E
Control button Button value Method called
Play btPlay Play
Record btRecord StartRecording
Stop btStop Stop
Next btNext Next
Prev btPrev Previous
Step btStep Step
Back btBack Back
Pause btPause Pause
Eject btEject Eject
Empty property
Applies to
TBitmap, TGraphic, TIcon, TMetafile objects
Declaration
property Empty: Boolean;
Read-only. The Empty property specifies whether the graphics object contains a graphic.
If Empty is True, no graphic has been loaded into the graphics object. If Empty is False, a
graphic is contained by the graphics object.
Example
The following loads a file into Graphic1 if it does not already contain a graphic.
if Graphic1.Empty then Graphic1.LoadFromFile('myfile.bmp');
See also
LoadFromFile method
EmptyTable method
Applies to
TTable component
Declaration
procedure EmptyTable;
The EmptyTable method deletes all records from the database table specified by
TableName. Before calling this method, the DatabaseName, TableName and TableType
properties must be assigned values.
Note If the table is open, it must have been opened with the Exclusive property set to True.
Example
with Table1 do
begin
Active := False;
DatabaseName := ‘Delphi_Demos’;
TableName := ‘CustInfo’;
TableType := ttParadox;
EmptyTable;
end;
EnableControls method
Applies to
TTable, TQuery, TStoredProc components
See also
Enabled property
Enabled property
Applies to
All controls; TDataSource, TForm, TMenuItem, TTimer components
The Enabled property determines if the control responds to mouse, keyboard, or timer
events, or if the data-aware controls update each time the dataset they are connected to
changes.
Example
To disable a button called FormatDiskButton,
FormatDiskButton.Enabled := False;
This code alternately dims or enables a menu command when a user clicks the button:
procedure TForm1.Button1Click(Sender: TObject);
begin
if OpenCommand.Enabled then
OpenCommand.Enabled := False
else
OpenCommand.Enabled := True;
end;
Description
Enabled specifies if the display in data-aware controls connected to TDataSource is
updated when the current record in the dataset changes. For example, when Enabled is
True and the Next method of a dataset component is called many times, each call
updates all controls. Setting Enabled to False allows the Next calls to be made without
performing updates to the controls. Once you reach the desired record, set Enabled to
True to update the controls to that record.
Note Setting Enabled to False clears the display in data-aware controls until you set it to True
again. If you want to leave the controls with their current contents while moving
through the table or query, call the DisableControls and EnableControls.
Example
DataSource1.Enabled := False;
while not DataSource1.DataSet.EOF do DataSource1.DataSet.Next;
DataSource1.Enabled := True;
EnabledButtons property
Declaration
property EnabledButtons: TButtonSet;
The EnabledButtons property determines which buttons on the media player are enabled.
An enabled button is colored and usable. A disabled button is dimmed and not usable.
If a button is not enabled with EnabledButtons, it is disabled. By default, all buttons are
enabled.
Example
The following example enables all of the media player component’s buttons:
TMediaPlayer1.EnabledButtons := [btPlay, btPause, btStop, btNext, btPrev, btStep, btBack,
btRecord, btEject]
See also
ColoredButtons property, VisibleButtons property
Example
This example uses a button and a label on a form. When the user clicks the button, a
specified date is encoded as a MyDate variable of type TDateTime. MyDate is then
displayed as a string in the caption of the label.
procedure TForm1.Button1Click(Sender: TObject);
var
MyDate: TDateTime;
begin
MyDate := EncodeDate(83, 12, 31);
Label1.Caption := DateToStr(MyDate);
end;
See also
DateToStr function, DecodeDate procedure, EncodeTime function
fractional part of a day given by the specified time. The value 0 corresponds to
+
midnight, 0.5 corresponds to noon, 0.75 corresponds to 6:00 pm, etc. +
Example +
procedure TForm1.Button1Click(Sender: TObject);
var
MyTime: TDateTime;
+
Hour, Min, Sec, MSec: Word;
begin
E
MyTime := EncodeTime(0, 45, 45, 7);
Label1.Caption := TimeToStr(MyTime);
Time24Hour := True;
Label2.Caption := TimeToStr(MyTime);
end;
See also
DecodeTime procedure, EncodeDate function
EndDoc method
Applies to
TPrinter object
Declaration
procedure EndDoc;
The EndDoc method ends the current print job and closes the text file variable. After the
application calls EndDoc, the printer begins printing. Use EndDoc after successfully
sending a print job to the printer. If the print job isn’t successful, use the Abort method.
The Close procedure calls the EndDoc method.
Example
This example uses a button on a form. When the user clicks it, the event handler prints a
rectangle on the printer and displays a message on the form.
procedure TForm1.Button1Click(Sender: TObject);
begin
with Printer do
begin
BeginDoc;
Canvas.Rectangle(20, 20, 400, 300);
EndDoc;
end;
Canvas.TextOut(10, 10, 'Printed');
end;
To use the EndDoc method, you must add the Printers unit to the uses clause of your
unit.
See also
BeginDoc method
EndDrag method
Applies to
All controls
Declaration
procedure EndDrag(Drop: Boolean);
The EndDrag method stops an object from being dragged any further. If the Drop
parameter is True, the object being dragged is dropped. If the Drop parameter is False,
the object is not dropped and dragging is canceled.
Example
The following code cancels the dragging of Label1 without dropping the object.
Label1.EndDrag(False);
See also
BeginDrag method, DragMode property, OnEndDrag event
EndMargin property
Applies to
TTabSet component
Declaration
property EndMargin: Integer;
The EndMargin property determines how far in pixels the rightmost tab appears from
the right edge of the tab set control. The default value is 5. Together with the StartMargin
property, EndMargin can play a role in determining how many tabs can fit within the tab
set control.
If AutoScroll is True and scroll buttons appear in the tab set control, EndMargin
determines how far in pixels the rightmost tab appears from the left edge of the scroll
buttons, rather than the edge of the tab set control.
See also
StartMargin property
EndPage property
Applies to
TReport component
Declaration
property EndPage: Word;
The value of the EndPage property specifies the last page of the report that is printed.
The default value is 9999. If the report is fewer than 9999 pages and you don’t change
the value of EndPage, your entire report is printed.
Example
The following code prints only the first page of Report1.
Report1.EndPage := 1;
Report1.Run;
See also
PrintCopies property, StartPage property
EndPos property
Applies to
TMediaPlayer component
Declaration
property EndPos: Longint;
Run-time only. The EndPos property specifies the position within the currently loaded
medium at which to stop playing or recording. EndPos is specified using the current
time format, which is specified in the TimeFormat property.
The EndPos property affects only the next Play or StartRecording method called after
setting EndPos. You must reset EndPos to affect any subsequent calls to Play or
StartRecording.
Example
The following procedure begins playing the .WAV audio file from the beginning of the
file to middle only.
procedure TForm1.Button1Click(Sender: TObject);
begin
with MediaPlayer1 do
begin
FileName := 'D:\WINAPPS\SOUNDS\CARTOON.WAV';
Open;
EndPos := TrackLength[1] div 2;
Play;
end;
end;
See also
StartPos property
EndUpdate method
Applies to
TStringList, TStrings objects; TOutline component
Declaration
procedure EndUpdate;
The EndUpdate method re-enables screen repainting and outline item reindexing that
was turned off with the BeginUpdate method.
Example
BeginUpdate and EndUpdate should always be used in conjunction with a try...finally
statement to ensure that EndUpdate is called if an exception occurs. A block that uses
BeginUpdate and EndUpdate typically looks like this:
ListBox1.Items.BeginUpdate;
try
ListBox1.Items.Clear;
ListBox1.Items.Add(...);
...
ListBox1.Items.Add(...);
finally
Example
var
F1, F2: TextFile;
Ch: Char;
begin
if OpenDialog1.Execute then begin
AssignFile(F1, OpenDialog1.Filename);
Reset(F1);
if SaveDialog1.Execute then begin
AssignFile(F2, OpenDialog1.Filename);
Rewrite(F2);
while not Eof(F1) do
begin
Read(F1, Ch);
Write(F2, Ch);
end;
CloseFile(F2);
end;
CloseFile(F1);
end;
end;
See also
Eoln function, SeekEof function
EOF property
Applies to
TTable, TQuery, TStoredProc components
Declaration
property EOF: Boolean;
Run-time and read only. EOF is a Boolean property that indicates whether a dataset is
known to be at its last row. The EOF property returns a value of True after:
• An application opens an empty dataset
• A call to a table’s Last method
• A call to a table’s Next fails because the cursor is on the last row
Example
Table1.First;
while not Table1.EOF do
begin
{Do Something}
Table1.Next;
end;
See also
MoveBy method
Description
The EOverflow exception is a floating-point math exception. It occurs when a calculated
result is too large to fit within the register allocated for it and therefore, data is lost. For
example, this code results in an overflow condition:
var
X, Y: Single;
begin
X := 3.3e37;
Y := 2.4e36;
X := X * Y;
end;
Exception Meaning
EFault The base exception object from which all fault objects descend.
EGPFault A general protect fault, which is usually caused by an uninitialized pointer or object.
EStackFault Illegal access to the processor’s stack segment.
EPageFault The Windows memory manager was unable to correctly use the Windows swap file.
EInvalidOpCode The processor encountered an undefined instruction. Usually this means the
processor was trying to execute data or uninitialized memory.
EBreakpoint Your application generated a breakpoint interrupt.
ESingleStep Your application generated a single-step interrupt.
You should rarely encounter the fault exceptions, other than the general protection fault,
because they represent serious failures in the operating environment. The breakpoint
and single-step exceptions are usually handled by Delphi’s integrated debugger.
Description
The ERangeError exception is an integer math exception. It occurs when an integer
expression evaluates to a value that exceeds the bounds of the specified integer type to
which it is assigned. For example, this code raises an ERangeError exception:
var
SmallNumber: Shortint;
X, Y: Integer;
begin
X := 100;
Y := 75;
SmallNumber := X * Y;
end;
Attempting to access an item in an array with an index value that is not within the
defined array results in a range error exception. For example, this code attempts to
assign a value to Values[11] when the highest index of the Values array is 10:
var
Values: array{1..10] of Integer;
I: Integer;
begin
for I := 1 to 11 do
Values[I] := I; { on the last loop a range error exception is raised }
end;
The ERangeError exception is raised only if range checking is turned on (your code
includes the $R+ directive or you set the Range-checking option using the Options|
Project dialog box).
Example
procedure TForm1.Button1Click(Sender: TObject);
var
F: Textfile;
begin
OpenDialog1.Title := 'Delete File';
if OpenDialog1.Execute then begin
AssignFile(F, OpenDialog1.FileName);
try
Reset(F);
if MessageDlg('Erase ' + OpenDialog1.FileName + '?',
mtConfirmation, [mbYes, mbNo], 0) = mrYes then
end;
MessageDlg('File I/O error.', mtError, [mbOk], 0); +
end;
end;
E
See also
Rename procedure
EraseSection method
Applies to
TIniFile object
Declaration
procedure EraseSection(const Section: string);
The EraseSection method erases an entire section of an .INI file.
The Section constant identifies the section of the .INI file to erase. For example, the
WIN.INI for Windows contains a [Desktop] section.
Example
This examples erases the SaveSettings section in the MYAPP.INI file when the user
clicks the button on the form:
procedure TForm1.Button1Click(Sender: TObject);
var
MyAppIni: TIniFile;
begin
MyAppIni := TIniFile.Create('MYAPPINI.INI');
MyAppIni.EraseSection('SaveSettings');
MyAppIni.Free;
end;
See also
ReadSection method
Error property
Applies to
TMediaPlayer component
Declaration
property Error: Longint;
Run-time and read only. The Error property specifies the MCI error code returned by
the most recent media control method (Back, Close, Eject, Next, Open, Pause, PauseOnly,
Play, Previous, StartRecording, Resume, Rewind, Step, or Stop).
The error codes returned by media control methods are the same error codes returned
by the mciSendCommand function, which is documented in MMSYSTEM.HLP. The
message describing the error code is stored in the ErrorMessage property.
The value of Error is zero if the most recent media control method didn’t cause an error.
+
If a method results in an error, a value other than zero is stored in Error. If the error
occurs during the opening of the device, an EMCIDeviceError exception occurs.
+
Example
+
The following code opens, closes, then plays MediaPlayer1. If an error occurs, a message
window displays the error number.
+
procedure TForm1.BitBtn1Click(Sender: TObject);
var
E
MyErrorString: String;
begin
MediaPlayer1.Open;
MediaPlayer1.Close;
MediaPlayer1.Play;
MyErrorString := 'ErrorCode: ' + IntToStr(Error);
MessageDlg(MyErrorString, mtError, [mbOk], 0);
end;
See also
ExitCode variable, ExitProc variable
ErrorMessage property
Applies to
TMediaPlayer component
Declaration
property ErrorMessage: String;
Run-time and read only. The ErrorMessage property specifies the error message that
describes the error code returned from the most recent media control method (Back,
Close, Eject, Next, Open, Pause, PauseOnly, Play, Previous, StartRecording, Resume, Rewind,
Step, or Stop). The error code described by the message is stored in the Error property.
Example
The following code opens MediaPlayer1. If an exception occurs, a message window
displays the error number and string.
procedure TForm1.BitBtn1Click(Sender: TObject);
var
MyErrorString: String;
begin
try
MediaPlayer1.Open;
except
MyErrorString := 'ErrorCode: ' + IntToStr(Error) + #13#10;
MessageDlg(MyErrorString + MediaPlayer1.ErrorMessage, mtError, [mbOk], 0);
end;
end;
Description
The EStackFault exception is a hardware fault exception. It occurs when an illegal
attempt to access the processor’s stack is made. Usually a stack fault represents a serious
failure in the operating environment.
If you have stack checking turned on {$S+}, you are not likely to reach a point where a
+
stack fault occurs because each procedure or function call checks to be sure there is
enough stack space for local variables before it runs. If stack checking is off {$S-}, this
+
checking does not occur, and the stack fault exception could be raised. +
EStreamError object Classes
+
Declaration
E
EStreamError = class(Exception);
The EStreamError exception is raised when an error occurs when a stream is read with
the LoadFromStream method. It also is the parent of these two stream exceptions:
Exception Description
EFCreateError An error occurred while creating a file
EFOpenError An error occurred while opening a file
The EWriteError exception is raised when the WriteBuffer method of a stream object is
unable to write the number of bytes specified in its Count parameter.
The CreateResHelp method obtains the string that becomes the value of the Message
+
property from a resource file. Specify the string as the value of the Ident parameter. The
AHelpContext parameter is for a context-sensitive ID number.
+
The CreateResFmtHelp method obtains the string that becomes the value of the Message +
property and formats it using the Format function. The AHelpContext parameter is for a
context-sensitive ID number. +
Exchange method
E
Applies to
TList, TStringList, TStrings objects
Declaration
procedure Exchange(Index1, Index2: Integer);
The Exchange method exchanges the position of two items in the list of a list object, or in
the list of strings of a string or string list object. The items are specified with their index
values in the Index1 and Index2 parameters. Because the indexes are zero-based, the first
item in the list has an index value of 0,the second item has an index value of 1, and so on.
If a string in a string or string list object has an associated object, Exchange changes the
position of both the string and the object.
Example
This example uses a list box that contains several strings as the value of the Items
property, and a button. When the user clicks the button, the second and third items in
the list box switch places in the list box.
procedure TForm1.Button1Click(Sender: TObject);
begin
ListBox1.Items.Exchange(1, 2);
end;
See also
Add method, AddStrings method, Delete method, IndexOf method, Insert method, Move
method
The construct Exclude (S, I) corresponds to S := S – (I) but the Exclude procedure
generates more efficient code.
See also
Include procedure
Exclusive property
Applies to
TTable component
Declaration
property Exclusive: Boolean;
Set the Exclusive property to True to prevent any other user from accessing the table. If
other users are accessing the table when you try to open it, your exception handler will
have to wait for those users to release it. If you do not provide an exception handler and
another user already has the table open, your application will be terminated.
Note Set the Active property to False before changing Exclusive to prevent an exception.
Do not set Active and Exclusive to True in the Object Inspector Window. Since the Object
Inspector will have the table open, that will prevent your program from opening it.
Set Exclusive to True only when you must have complete control over the table.
Example
{ Try to open Table1 with Exclusive True }
{ First, close Table1 }
Table1.Active := False;
repeat { until successful or Cancel button is pressed }
try
Table1.Exclusive := True; { See if it will open }
Table1.Active := True;
Break; { If no error, exit the loop }
except
on EDatabaseError do
{ Ask if it is OK to retry }
if MessageDlg(‘Could not open Table1 exclusively - OK to retry?’, mtError,
[mbOK, mbCancel], 0) <> mrOK then raise; { If not, reraise to abort }
{ Otherwise resume the repeat loop }
end;
until False;
Example
{ Execute the stored procedure }
StoredProc1.ExecProc;
ExecSQL method
Applies to
TQuery component
Declaration
procedure ExecSQL;
Use the ExecSQL method to execute an SQL statement assigned to the SQL property of a
TQuery if the statement does not return a result set. If the SQL statement is an INSERT,
UPDATE, DELETE, or any DDL statement, then use this method.
If the SQL statement is a SELECT statement, use Open instead.
Example
Query1.Close;
Query1.SQL.Clear;
Query1.SQL.Add(‘Delete from Country where Name = ‘Argentina’);
Query1.ExecSQL;
Execute method
Applies to
TBatchMove, TColorDialog, TFindDialog, TFontDialog, TOpenDialog, TPrintDialog,
TPrinterSetupDialog, TReplaceDialog, TSaveDialog components
For Color, Font, Open, Save, Print, Find, and Replace dialog boxes
Declaration
function Execute: Boolean;
The Execute method displays the dialog box in the application and returns True when it
is displayed. This allows your code to determine whether the user has displayed and
used the dialog box by choosing its OK button.
Example
This example uses a main menu component, a memo, an Open dialog box, and a Save
dialog box on a form. To use it, you need to create a File menu that includes an Open
command. This code is an event handler for the OnClick event of the Open command on
the File menu. If the user has selected a file name by choosing the Open dialog box’s OK
button, the code sets the Save dialog box Filename property to the same file name, and
displays the selected file name as the caption of the form.
procedure TForm1.Open1Click(Sender: TObject);
begin
if OpenDialog1.Execute then
begin
Memo1.Lines.LoadfromFile(OpenDialog1.FileName);
SaveDialog1.Filename := OpenDialog1.FileName;
Caption := OpenDialog1.FileName;
end;
end;
Example
This code displays the Printer Setup dialog box when the user clicks the button:
procedure TForm1.Button1Click(Sender: TObject);
begin
PrinterSetupDialog1.Execute;
end;
The Execute method performs the batch move operation specified by Mode from the
+
Source table to the Destination table. +
Example +
BatchMove1.Execute;
+
ExecuteMacro method E
Applies to
TDDEClientConv component
Declaration
function ExecuteMacro(Cmd: PChar; WaitFlg: Boolean): Boolean;
The ExecuteMacro method attempts to send a macro command string to a DDE server
application. ExecuteMacro returns True if the macro was successfully passed to the DDE
server application. If ExecuteMacro was unable to send a command string, ExecuteMacro
returns False.
Cmd is a null-terminated string that contains the macro to be executed by the DDE
server application. The actual value of Cmd depends on the DDE server application. See
the documentation of the DDE server application for the command strings it will accept.
WaitFlg determines if your application should wait until the DDE server application
finishes executing the macro before allowing another successful call to ExecuteMacro or
the ExecuteMacroLines, PokeData, or PokeDataLines methods. If WaitFlg is set to True,
subsequent calls to these methods before the DDE server application completes the first
macro do not send data to the DDE server and return False. If WaitFlg is set to False,
subsequent calls to these methods before the DDE server application completes the first
macro do attempt to send data to the DDE server.
If you need to send a macro command string list rather than a single string, use the
ExecuteMacroLines method.
Note Depending on the DDE server, attempting to execute a macro or poke data before the
DDE server application completes the first macro might cause the first macro to execute
unsuccessfully or produce unpredictable results. See the documentation of the DDE
server application for the results of sending command strings or poking data before
macro execution has completed.
Example
The following code executes the macro that is specified by the Text of Edit1. The macro
sets WaitFlg to True to wait until the server has completed macro execution.
var
TheMacro: PChar;
begin
StrPCopy(TheMacro, Edit1.Text);
DDEClientConv1.ExecuteMacro(TheMacro, True);
end;
See also
StrPCopy function
ExecuteMacroLines method
Applies to
TDDEClientConv component
Declaration
function ExecuteMacroLines(Cmd: TStrings; WaitFlg: Boolean): Boolean;
The ExecuteMacroLines method attempts to send a macro command string list to a DDE
server application. ExecuteMacroLines returns True if the macro was successfully passed
to the DDE server application. If ExecuteMacroLines was unable to send a command
string list, ExecuteMacroLines returns False.
Cmd contains the macro to be executed by the DDE server application. WaitFlg
determines if your application should wait until the DDE server application finishes
executing the macro before allowing another successful call to ExecuteMacroLines or the
ExecuteMacro, PokeData, or PokeDataLines methods.
Use ExecuteMacroLines to execute a macro command string list rather than a single
macro command string (which is what the ExecuteMacro method passes for its Cmd
parameter).
Example
The following code executes the macro that exists in the Lines of Memo1. Wait is a
boolean variable that specifies whether to wait for the server to complete macro
processing before sending more data to the server.
DDEClientConv1.ExecuteMacroLines(Memo1.Lines, Wait);
ExeName property
Applies to
TApplication component
Declaration
property ExeName: string;
Run-time and read only. The ExeName property contains the name of the executable
application including path information. The name of the application is the name you
gave the project file with an .EXE extension. If you haven’t specified a name, the default
name is PROJECT1.EXE.
If the current block is a procedure or function, Exit causes the calling block to continue
with the statement after the point which the block was called.
Example
uses WinCrt;
procedure TForm1.Button1Click(Sender: TObject);
begin
repeat
if Keypressed then Exit;
Write('Xx');
until False;
end;
See also
Halt procedure
See also
ErrorAddr variable, ExitProc variable
When implemented properly, an exit procedure actually becomes part of a chain of exit
+
procedures. The procedures on the exit chain get executed in reverse order of
installation.
+
To keep the exit chain intact, you need to save the current contents of ExitProc before +
changing it to the address of your own exit procedure.
The first statement in your exit procedure must reinstall the saved value of ExitProc. +
See also E
ErrorAddr variable, ExitCode variable
Return Value
The Exp function returns the exponential of X.
The return value is e raised to the power of X, where e is the base of the natural
logarithms.
Example
var
S: string;
begin
S := ‘e = ‘ + IntToStr(Exp(1.0));
TextOut(10, 10, S);
end;
See also
Ln function
Expand method
Applies to
TList, TOutlineNode objects
For lists
Declaration
function Expand: TList;
The Expand method increases the maximum size of the list maintained by a list object,
creating more space to add new list items and incrementing the value of the Capacity
property. If the value of the Capacity property is greater than 8, the Expand method
increases the capacity of the list by 16. If the value of Capacity is greater than 4, but less
than 9, then the capacity of the list increases by 8. Finally if the value of Capacity is less
than 4, then the capacity of the list grows by 4.
The returned value is the expanded list.
Example
The following code expands List1.
List1.Expand;
See also
Capacity property
Example
The following code expands the first child of the first outline item, if it has children.
with Outline1.Items[1] do
if HasItems then
Outline1.Items[GetFirstChild].Expand;
See also
Collapse method, FullCollapse method, FullExpand method, PictureMinus property,
PictureOpen property
Expanded property
Applies to
TOutlineNode object
Declaration
property Expanded: Boolean;
Run-time only. The Expanded property specifies whether the outline item is expanded or
+
not. When an outline item is expanded, its subitems are displayed and the minus picture
or open picture might be displayed, depending on the outline style specified in the
+
OutlineStyle property of the TOutline component. +
Expanded is True if the item is expanded, False if it isn’t expanded.
+
Example
The following code toggles the state of the selected outline item. E
with Outline1 do
Items[SelectedItem].Expanded := not Items[SelectedItem].Expanded;
See also
Collapse method, Expand method, FullCollapse method, FullExpand method, PictureMinus
property, PictureOpen property
Example
The following code converts a file name into a fully-expanded file name:
MyFileName := ExpandFileName(MyFileName);
See also
ExtractFileName function
Expression property
Applies to
TIndexDef object
Declaration
property Expression: string;
Run-time and read only. Read expressions in dBASE indexes.
ExtendedSelect property
Applies to
TListBox component
Declaration
property ExtendedSelect: Boolean;
The ExtendedSelect property determines if the user can select an range of items in the list
box. ExtendedSelect works in conjunction with the MultiSelect property. If MultiSelect is
False, the setting of ExtendedSelect has no effect as the user will not be able to select more
than one item at a time in the list box.
If MultiSelect is True and ExtendedSelect is True, the user can select an item then hold
down the Shift key and select another and all the items in between the two selected items
also become selected. If the user doesn’t hold down the Shift or Ctrl key while selecting a
second item, the first selected item becomes unselected—in other words, the user must
use the Ctrl key to select multiple noncontiguous items, or the Shift key to select a range of
items. If ExtendedSelect is False, the user can select multiple items without using the Shift
or Ctrl key, but they can’t select a range of items in one operation.
See also
MultiSelect property
Example
The following code returns the extension from a file name:
MyFilesExtension := ExtractFileExt(MyFileName);
See also
ExtractFileName function
The ExtractFileName function takes a fully or partially qualified path name in FileName
+
and returns a string containing only the file name part, including the name and
extension.
+
Example
+
The following code changes the caption of Form1 to read "Editing <FileName>". +
E
Form1.Caption := 'Editing '+ ExtractFileName(FileName);
See also
ExpandFileName function, ExtractFilePath function
Example
The following code changes the current directory to the location of FileName.
ChDir(ExtractFilePath(FileName));
See also
ExtractFileName function
Description
The EZeroDivide exception is a floating-point math exception. It occurs when your
application attempts to divide a floating-point value by zero. For example, this code
raises a EZeroDivide exception:
var
X, Y: Double;
begin
X := 0.0;
Y := 10.11111;
Y := Y / X;
end;
See also
New procedure
FieldByName method
Applies to
TTable, TQuery, TStoredProc components
Declaration
function FieldByName(const FieldName: string): TField;
The FieldByName method returns the TField with the name passed as the argument in
FieldName. Using FieldByName protects your application from a change in the order of
the fields in the dataset. If the field can not be found, FieldByName raises an exception. If
you are not certain whether a field with the requested name exists, use the FindField
method.
Example
with Table1 do
begin
{ This is the safe way to change ‘CustNo’ field }
FieldByName(‘CustNo’).AsString := ‘1234’;
{ This is *not* the safe way to change ‘CustNo’ field }
Fields[0].AsString := ‘1234’;
end;
FieldClass property
Applies to
TFieldDef object
Declaration
property FieldClass: TFieldClass;
Run-time and read only. Read FieldClass to determine the type of the TField component
that corresponds to this TFieldDef object.
FieldCount property
Applies to
TDBGrid, TDBLookupList, TQuery, TStoredProc, TTable components
Declaration
property FieldCount: Integer;
Run-time and read only. The FieldCount property specifies the number of fields
(columns) in a dataset. It may not be the same as the number of fields in the underlying
database table, since you can add calculated fields and remove fields with the Fields
Designer.
For the data grid and database lookup list box, the value of the FieldCount property is the
number of fields in the dataset displayed in the control.
Example
The following code displays the number of fields in DBGrid1 in a label.
Label1.Caption := IntToStr(DBGrid1.FieldCount);
See also
Fields property, SelectedField property
FieldDefs property
Applies to
TTable, TQuery, TStoredProc components
Declaration
property FieldDefs: TFieldDefs;
Run-time only. The FieldDefs property holds information about each TFieldDef in the
dataset. You can use this property to determine which fields are in the dataset, their
name, type, and size.
See also
Fields property, TField component
See also
DisplayName property
FieldNo property
Applies to
TFieldDef object; TBCDField, TBlobField, TBooleanField, TBytesField, TCurrencyField,
TDateField, TDateTimeField, TFloatField, TGraphicField, TIntegerField, TMemoField,
TSmallintField, TStringField, TTimeField, TVarBytesField, TWordField components
Example
{ Display the field name and number }
with FieldDef1 do
MessageDlg(Name + ' is field ’ + IntToStr(FieldNo), mtInformation, [mbOK], 0);
See also
TField component
For fields
Declaration
property FieldNo: Integer;
Run-time and read only. FieldNo is the ordinal of the TField component in its dataset.
This property is available for programs that make direct calls to the Borland Database
Engine.
Fields property
Applies to
TIndexDef object; TDBGrid, TDBLookupList, TQuery, TStoredProc, TTable components
Example
The following code left justifies the first field in DBGrid1.
DBGrid1.Fields[0].Alignment := taLeftJustify;
See also
FieldCount property, FieldDefs property, SelectedField property, SelectedIndex property
Constant Definition
fmOpenRead Open for read access only.
fmOpenWrite Open for write access only.
fmOpenReadWrite Open for read and write access.
fmShareCompat Compatible with the way FCBs are opened.
fmShareExclusive Read and write access is denied.
fmShareDenyWrite Write access is denied.
fmShareDenyRead Read access is denied.
fmShareDenyNone Allows full access for others.
Example
The following code closes a file opened with FileOpen:
FileClose(MyFileHandle);
See also
FileCreate function, FileOpen procedure
Example
The following example creates a new file and assigns it to the identifier MyFileHandle.
MyFileHandle := FileCreate('NEWFILE.TXT');
See also
FileClose procedure, FileOpen procedure
FileEdit property
Applies to
TFileListBox component
Declaration
property FileEdit: TEdit;
The FileEdit property provides a simple way to display a file selected in a file list box as
the text of an edit box, as is commonly done in Open and Save dialog boxes. If no file is
selected in the file list box, the text of the edit box is the current value of the file list box’s
+
Mask property. +
Specify the edit box you want the mask or selected file to appear in as the value of the
FileEdit property. +
Example +
This example uses a button, an edit box, a label, a drive combo box, a directory list box, a
file list box, and a filter combo box on a form. When the user clicks the button, the rest of
the controls of the form begin working together like the controls in an Open or Save
+
dialog box. F
procedure TForm1.Button1Click(Sender: TObject);
begin
DriveComboBox1.DirList := DirectoryListBox1;
DirectoryListBox1.FileList := FileListBox1;
DirectoryListBox1.DirLabel := Label1;
FileListBox1.FileEdit := Edit1;
FilterComboBox1.FileList := FileListBox1;
end;
See also
DirLabel property, DirList property, FileList property, Mask property, Text property
FileEditStyle property
Applies to
TOpenDialog, TSaveDialog components
Declaration
property FileEditStyle: TFileEditStyle;
The FileEditStyle property determines if the Open or Save dialog box contains an edit
box or combo box control for the user to enter a file name. These are the possible values:
Value Meaning
fsEdit Edit box to enter a file name.
fsComboBox Drop-down combo box to enter a file name. The combo box can be used to display a
list of file names.
1 Add a TStringList object to your application to keep the list of file names the user
enters.
2 Before your application calls the Execute method to display the Open or Save dialog
box, assign the TStringList object to the HistoryList property. For example,
var
MyHistoryList: TStringList;
begin
OpenDialog1.HistoryList := MyHistoryList;
if OpenDialog1.Execute then
...
3 Use the returned FileName property value to update your history list. For example:
MyHistoryList.Insert(0, OpenDialog1.FileName);
Example
This examples uses a Save dialog box, an edit box, and a button on a form. When the
user clicks the button, the Save dialog box appears with a combo box control to allow
the user to type a file name, select a file name from the list box, or drop down a list to
choose a file name from a history list. For this example, no history list exists. Once the
user selects a file name, the selected name appears in the edit box on the form.
procedure TForm1.Button1Click(Sender: TObject);
begin
SaveDialog1.FileEditStyle := fsComboBox;
SaveDialog1.Filter := 'Text Files(*.TXT) | *.TXT';
if SaveDialog1.Execute then
Edit1.Text := SaveDialog1.FileName;
end;
See also
HistoryList property, TFilterComboBox component
Example
The following code prompts you for confirmation before deleting a file:
if FileExists(FileName) then
MsgBox('Do you really want to delete ' + ExtractFileName(FileName)
+ '?'), []) = IDYes then FileDelete(FileName);
See also
DateTimeToFileDate function
See also
FileSetAttr function
See also
FileSetDate procedure
FileList property
Applies to
TDirectoryListBox, TFilterComboBox components
Declaration
property FileList: TFileListBox;
The FileList property is used for two different purposes, depending on the type of
control it is a property of.
For directory list boxes, FileList provides a simple way to connect a directory list box
with a file list box. Once the two controls are connected and new directory is selected as
the current directory using a directory list box, the file list box displays the files in the
current directory. Specify the file list box in which you want to display the files in the
directory selected in the directory list box as the value of the FileList property.
For filter combo boxes, FileList provides a simple way to connect a filter combo box with
a file list box. Once the two controls are connected and a new filter is selected using a
filter combo box, the file list box displays the files that match the selected filter. Specify
the file list box you want to display the files matching the selected filter as the value of
the FileList property.
Example
This example uses a button, an edit box, a label, a drive combo box, a directory list box, a
file list box, and a filter combo box on a form. When the user clicks the button, the rest of
the controls on the form begin working together like the controls in an open or save
dialog box.
procedure TForm1.Button1Click(Sender: TObject);
begin
DriveComboBox1.DirList := DirectoryListBox1;
DirectoryListBox1.FileList := FileListBox1;
DirectoryListBox1.DirLabel := Label1;
FileListBox1.FileEdit := Edit1;
FilterComboBox1.FileList := FileListBox1;
end;
See also
DirLabel property, Directory property, DirList property, FileEdit property, FileList
property, Filter property, Mask property
The FileMode variable determines the access code to pass to DOS when typed and
+
untyped files (not text files) are opened using the Reset procedure. +
The default FileMode is 2. Assigning another value to FileMode causes all subsequent
Resets to use that mode. +
The range of valid FileMode values depends on the version of DOS in use. For all
versions, these modes are defined: +
0 Read only +
1
2
Write only
Read/Write F
DOS version 3.x and later defines additional modes, which are primarily concerned
with file sharing on networks.
See also
Rewrite procedure
FileName property
Applies to
TFileListBox, TMediaPlayer, TOpenDialog, TSaveDialog components; TIniFile object
Example
This example displays an Open dialog box and suggests the file name LIST.PAS to the
user. Once the user selects a file name, the code displays that name in a label on the
form:
procedure TForm1.Button1Click(Sender: TObject);
begin
OpenDialog1.FileName := ’LIST.PAS’;
if OpenDialog1.Execute then
Label1.Caption := OpenDialog1.FileName;
end;
See also
Files property
Example
The following code determines what type of media device to open from the results of an
Open dialog box, then opens the file.
if OpenDialog1.Execute then
begin
MediaPlayer1.DeviceType := dtAutoSelect;
MediaPlayer1.FileName := OpenDialog1.FileName;
MediaPlayer1.Open;
end;
Example
This example uses a file list box and a label on a form. When the user selects a file in the
file list box, the name of the file appears as the caption of the label.
procedure TForm1.FileListBox1Click(Sender: TObject);
begin
Label1.Caption := FileListBox1.FileName;
end;
See also
FileList property
Position Result
Beginning of file FilePos(F) = 0
Middle of file FilePos(F) = current file position
End of file Eof(F) = True
{$I+} lets you handle run-time errors using exceptions. For more information on
handling run-time library exceptions, see Handling RTL Exceptions in the Help system.
If you are using {$I–}, you must use IOResult to check for I/O errors.
Example
var
f: file of Byte;
size : Longint;
S: string;
y: integer;
begin
if OpenDialog1.Execute then begin
AssignFile(f, OpenDialog1.FileName);
Reset(f);
size := FileSize(f);
S := 'File size in bytes: ' + IntToStr(size);
y := 10;
Canvas.TextOut(5, y, S);
y := y + Canvas.TextHeight(S) + 5;
S := 'Seeking halfway into file...';
Canvas.TextOut(5, y, S);
y := y + Canvas.TextHeight(S) + 5;
See also
FileSize function, Seek procedure
Example
The following code fills a buffer from a file.
ActualRead := FileRead(MyFileHandle, Buffer, SizeOf(Buffer));
See also
FileSeek function, FileWrite function
Files property
Applies to
TOpenDialog, TSaveDialog components
Declaration
property Files: TStrings;
Run-time and read only. The Files property value contains a list of all the file names
selected in the Open or Save dialog box including the path names.
To let users select multiple file names in the dialog box, include ofAllowMultiSelect in the
Options property set (set ofAllowMultiSelect to True).
The entire list of names is returned as the value of the FileName property. If the list of
names is long, FileName contains only the first 127 characters.
Example
The following code searches for FINDME.DLL in a series of directories:
FoundIt := FileSearch('FINDME.DLL', MyAppDir+’\';'+WinDir+';'+WinDir+'\SYSTEM');
See also
FileExists function
denoting the beginning of the file, the end of the file, and the current position of the file
pointer.
Origin Action
0 The file pointer is positioned Offset bytes from the beginning of the file.
1 The file pointer is positioned Offset bytes from its current position.
2 The file pointer is positioned Offset bytes from the end of the file.
If FileSeek is successful, it returns the new position of the file pointer; otherwise, it
returns the Windows constant HFILE_ERROR.
Example
The following code positions the file pointer at the end of a file:
if FileSeek(MyFileHandle,0,2) = HFILE_ERROR then
HandleFileError
else
AppendStuff;
See also
FileRead function, FileWrite function
See also
FileGetAttr function
Example
var
f: file of Byte;
size : Longint;
S: string;
y: integer;
begin
if OpenDialog1.Execute then begin
AssignFile(f, OpenDialog1.FileName);
Reset(f);
size := FileSize(f);
S := 'File size in bytes: ' + IntToStr(size);
y := 10;
Canvas.TextOut(5, y, S);
y := y + Canvas.TextHeight(S) + 5;
S := 'Seeking halfway into file...';
Canvas.TextOut(5, y, S);
y := y + Canvas.TextHeight(S) + 5;
Seek(f,size div 2);
S := 'Position is now ' + IntToStr(FilePos(f));
Canvas.TextOut(5, y, S);
CloseFile(f);
end;
end;
See also
FilePos function
FileType property
Applies to
TFileListBox component
Declaration
property FileType: TFileType;
The FileType property determines which files are displayed in the file list box based on
the attributes of the files. Because FileType is of type TFileType, which is a set of file
attributes, FileType can contain multiple values. For example, if the value of FileType is a
set containing the values ftReadOnly and ftHidden, only files that have the read-only and
hidden attributes are displayed in the list box. These are the values that can occur in the
FileType property:
Value Meaning
ftReadOnly When ftReadOnly is True, the list box can display files with the read-only attribute.
ftHidden When ftHidden is True, the list box can display files with the hidden attribute.
ftSystem When ftSystem is True, the list box can display files with the system attribute.
ftVolumeID When ftVolumeID is True, the list box can display the volume name.
ftDirectory When ftDirectory is True, the list box can display directories.
ftArchive When ftArchive is True, the list box can display files with archive attribute.
ftNormal When ftNormal is True, the list box can display files with no attributes.
If you use the Object Inspector to change the value of FileType, click the FileType
property to see the attribute values. Then you can set each value to True or False, which
builds the FileType set.
Example
This example uses a file list box on a form. When the application runs, only read-only
files, directories, volume IDs, and files with no attributes appear in the list box.
procedure TForm1.FormCreate(Sender: TObject);
begin
FileListBox1.FileType := [ftReadOnly, ftDirectory, ftVolumeID, ftNormal];
end;
See also
Mask property, TFileType type
Example
var
S: string[80];
begin
{ Set a string to all spaces }
FillChar(S, SizeOf(S), ' ');
S[0] := #80; { Set length byte }
end;
See also
Move procedure
FillRect method
Applies to
TCanvas object
Declaration
procedure FillRect(const Rect: TRect);
The FillRect method fills the specified rectangle on the canvas using the current brush.
Example
This code creates a rectangle on the form’s canvas and colors it red by changing the
canvas Brush property to clRed.
procedure TForm1.ColorRectangleClick(Sender: TObject);
var
NewRect: TRect;
begin
NewRect := Rect(20, 30, 50, 90);
Form1.Canvas.Brush.Color := clRed;
Form1.Canvas.FillRect(NewRect);
end;
See also
Brush property, Rect function
Filter property
Applies to
TFilterComboBox, TOpenDialog, TSaveDialog components
This allows the user to select from a number of file filters and determine which files are
+
displayed in the list box. +
To specify multiple file filters,
1 Create a file filter string as previously shown.
+
2 Type another file filter in the same way, but separate the second file filter from the
first with the | character.
+
3 Continue adding as many file filters as you like, separating them with the | character. +
The string can be up to 255 characters.
Here’s an example of three file filters specified as the value of the Filter property:
F
’Text files (*.TXT)|*.TXT|Pascal files (*.PAS)|*.PAS|Quattro Pro files (*.WB1)|*.WB1’
Now when the dialog box appears, the user can choose from three file filters that appear
in the List Files of Type drop-down list box.
Note that the previous example includes the file filters in parentheses in the text parts.
This isn’t required, but it’s a common convention that helps users understand what to
expect when they select a file filter.
You can string multiple wildcard file filters together if you separate them with
semicolons:
OpenDialog1.Filter := ’All files|*.TXT;*.PAS;*.WB1’;
Example
This code sets the value of the Filter property, displays the dialog box, and assigns the
file name the user selects to a variable:
procedure TForm1.Button1Click(Sender: TObject);
var
NameOfFile : TFileName;
begin
OpenDialog1.Filter := 'Text files (*.TXT)|*.TXT|Pascal files (*.PAS)' +
‘|*.PAS|Quattro Pro files (*.WB1)|*.WB1';
if OpenDialog1.Execute then
NameOfFile := OpenDialog1.FileName;
...
end;
See also
FileName property, FilterIndex property
A file mask or file filter is a file name that usually includes wildcard characters (*.PAS,
for example). When your application runs, the file filter the user selects in the filter
combo box becomes the value of the Mask property. To specify a file filter, assign a filter
string as the value of Filter. To create the string, follow these steps:
1 Type some meaningful text to indicate the type of file.
2 Type a | character (this is the “pipe” or “or” character).
3 Type the file filter.
Don’t put in any spaces around the | character in the string.
Here’s an example:
FilterComboBox1.Filter := ’Text files|*.TXT’;
If you entered this string, the string “Text files” appears in the filter combo box.
You can specify multiple file filters so that a list of filters appears in the filter combo box
from which the user can select. To specify multiple file filters,
1 Type a file filter as shown previously.
2 Type another file filter in the same way, but separate the second file filter from the
first with the | character.
3 Continue adding as many file filters as you like, separating them with the | character.
The string can be up to 255 characters.
Here’s an example of three file filters specified as the value of the Filter property:
’Text files (*.TXT)|*.TXT|Pascal files (*.PAS)|*.PAS|Quattro Pro files (*.WB1)|*.WB1’
Note that the previous example includes the file filters in parentheses in the text parts.
This isn’t required, but it’s a common convention that helps users understand what to
expect when they select a file filter.
You can string multiple wildcard file filters together if you separate them with
semicolons:
FilterComboBox1.Filter := ’All files|*.TXT;*.PAS;*.WB1’;
Examples
This example uses a filter combo box on a form. When the application runs, three filters
appear in the filter combo box:
procedure TForm1.FormCreate(Sender: TObject);
begin
FilterComboBox1.Filter := 'Text files (*.TXT)|*.TXT|Pascal files (*.PAS)' +
'|*.PAS|Quattro Pro files (*.WB1)|*.WB1';
end;
This example uses a filter combo box, a file list box, and an edit box on a form. The code
connects the three controls through the FileList and FileEdit properties. When the user
selects a filter in the filter combo box, the filter is applied to the files in the list box so the
list box displays only the files that match the filter. The filter in effect on the file list box
appears in the edit box. When the user selects a file in the file list box, the selected file
appears in the edit box.
Declaration
property FilterIndex: Integer;
The FilterIndex property determines which file filter specified in the Filter property
appears as the default file filter in the List Files of Type drop-down list box. For
example, if you set the FilterIndex value to 2, the second file filter listed in the Filter
property becomes the default filter when the dialog box appears. The default FilterIndex
value is 1. If you specify a value greater than the number of file filters in the Filter
property, the first filter is chosen.
The default value is 1.
Example
This code specifies three file filters as the value of the Filter property, sets the FilterIndex
to 2 so that the second file filter is the default file filter, and displays the Open dialog
box. Once the user selects a file with the dialog box and chooses OK, the file name the
user selected appears in a label on the form.
procedure TForm1.Button1Click(Sender: TObject);
begin
OpenDialog1.Filter := 'Text files (*.TXT)|*.TXT|Pascal files (*.PAS)' +
‘|*.PAS|dBASE program files (*.PRG)|*.PRG';
OpenDialog1.FilterIndex := 2;
if OpenDialog1.Execute then
Label1.Caption := OpenDialog1.FileName;
end;
See also
Filter property
Find method
Applies to
TFieldDefs, TStringList objects
Example
This example uses a list box and a label on a form. When the application runs, a string
list object is created and three strings are added to it. The Find method searches the
strings to look for a match with the string ’Flowers’. If the string is found, all the strings
in the string list are added to the list box, and the index value of the ’Flowers’ string
appears in the caption of the label control.
procedure TForm1.FormCreate(Sender: TObject);
var
MyList: TStringList;
Index: Integer;
begin
MyList := TStringList.Create;
MyList.Add('Animals');
MyList.Add('Flowers');
MyList.Add('Cars');
if MyList.Find('Flowers', Index) then
begin
ListBox1.Items.AddStrings(MyList);
Label1.Caption := 'Flowers has an index value of ' + IntToStr(Index);
end;
MyList.Free;
end;
See also
Add method, Clear method, IndexOf method, Strings property
See also
Name property
See also
FindFirst function, FindNext function
FindComponent method
Applies to
All components
Declaration
function FindComponent(const AName: string): TComponent;
The FindComponent method returns the component in the Components array property
with the name that matches the string in the AName parameter. FindComponent is not
case sensitive.
Example
To set up this example, place several components on a form, including an edit box and a
button. When the user clicks the button, the code displays the value of the
ComponentIndex of the edit box in the edit box.
procedure TForm1.Button1Click(Sender: TObject);
var
TheComponent: TComponent;
begin
TheComponent := FindComponent('Edit1');
Edit1.Text := IntToStr(TheComponent.ComponentIndex);
end;
See also
ComponentCount property, ComponentIndex property, Components property
FindDatabase method
Applies to
TSession component
Declaration
function FindDatabase(const DatabaseName: string): TDatabase;
The FindDatabase method attempts to find a TDatabase component in the Databases
collection with a DatabaseName property which matches the DatabaseName parameter. If
there is no such database, FindDatabase returns nil.
Example
MyDatabase := Session.FindDatabase(‘MYDB’);
See also
Session variable
FindField method
Applies to
TTable, TQuery, TStoredProc components
Declaration
function FindField(const FieldName: string): TField;
The FindField method returns the field with the name passed in FieldName. While calling
FindField is slightly slower than a direct reference to the Fields property, using FindField
protects your application from a change in the order of the fields in the component. If
+
the field can not be found, FindField returns nil. +
Example +
with Table1 do
begin
{ This is the safe way to change ‘CustNo’ field }
+
FindField(‘CustNo’).AsString := ‘1234’;
{ This is *not* the safe way to change ‘CustNo’ field }
+
Fields[0].AsString := ‘1234’;
end; F
See also
FieldByName method
You can combine attributes by adding their constants or values. For example, to search
for read-only and hidden files in addition to normal files, pass (faReadOnly + faHidden)
the Attr parameter.
FindFirst returns the results of the directory search in the search record you specify in
the F parameter. You can then use the fields of the search record to extract the
information you want.
The return value is zero if the function was successful. Otherwise the return value is a
negative DOS error code; a value of -18 indicates that there are no more files matching
the search criteria.
Example
This example uses a label and a button named Search on a form. When the user clicks
the button, the first file in the specified path is found and the name and number of bytes
in the file appear in the label's caption:
var
SearchRec: TSearchRec;
procedure TForm1.SearchClick(Sender: TObject);
begin
FindFirst('c:\delphi\bin\*.*', faAnyFile, SearchRec);
Label1.Caption := SearchRec.Name + ' is ' + IntToStr(SearchRec.Size) +
' bytes in size';
end;
See also
FindNext function
FindIndexForFields method
Applies to
TIndexDefs object
Declaration
function FindIndexForFields(const Fields: string): TIndexDef;
Run-time and read only. Returns the TIndexDef object that is present in Items
corresponding to a semicolon-separated list of fields.
FindItem method
Applies to
TMainMenu component
Declaration
function FindItem(Value: Word; Kind: TFindItemKind): TMenuItem;
The FindItem method returns the menu item owned by the menu that has either a menu
+
handle, menu command, or menu shortcut matching the value of the Value parameter.
The Kind parameter can be any of these values:
+
Value Meaning
+
fkCommand
fkHandle
Menu command number used by Windows WM_COMMAND message
Menu handle
+
fkShortCut Menu shortcut +
Example
This example uses a label, a button, and a main menu component. The menu is a File
F
menu that contains Open, Save, and Close commands. Delphi automatically names the
menu items that are the commands, Open1, Save1, and Close1. The Open1 menu item has
a ShortCut value of F3. The code locates the menu item that has the specified shortcut
and reports the name of the menu item in the caption of the label. Note that the shortcut
is specified as a virtual key code. You can find a list of virtual key codes in the Help
system. Search for the Virtual Key Codes topic.
procedure TForm1.Button1Click(Sender: TObject);
var
ItemName: TMenuItem;
begin
ItemName := MainMenu1.FindItem(VK_F3, fkShortCut);
Label1.Caption := ItemName.Name;
end;
See also
Command property, ShortCut property, TMenuItem component
FindKey method
Applies to
TTable component
Declaration
function FindKey(const KeyValues: array of const): Boolean;
The FindKey method searches the database table to find a record whose index fields match
those passed in KeyValues. FindKey takes a comma-delimited array of values as its
argument, where each value corresponds to a index column in the underlying table. The
values can be literals, variables, null, or nil. If the number of values supplied is less than
the number of columns in the database table, then the remaining values are assumed to
be null. FindKey will search for values specified in the array in the current index.
FindKey does the following:
• Puts the TTable in SetKey state.
• Finds the record in the table that matches the specified values. If a matching record is
found, it moves the cursor there, and returns True.
• If a matching record is not found, it does not move the cursor, and returns False.
Example
{ Search for CustNo = ‘1234’ }
if Table1.FindKey([‘1234’]) then
ShowMessage(‘Customer Found’);
See also
FindNearest method, GotoKey method
FindNearest method
Applies to
TTable component
Declaration
procedure FindNearest(const KeyValues: array of const);
The FindNearest method moves the cursor to the first record whose index fields’ values
are greater than or equal to those passed in KeyValues. The search begins at the first
record, not at the current cursor position. This method can be used to match columns of
string data type only. If you do not supply values for each field in the index key, any
unassigned fields will use a null value.
FindNearest works by default on the primary index column. To search the table for
values in other indexes, you must specify the field name in the table’s IndexFieldNames
property or the name of the index in the IndexName property.
The KeyExclusive property indicates whether a search will position the cursor on or after
the specified record being searched for.
Note With Paradox or dBASE tables, FindNearest works only with indexed fields. With SQL
databases, it can work with any columns specified in the IndexFieldNames property.
Example
{ Search for CustNo >= ‘1234’ }
Table1.FindNearest([‘1234’]);
See also
FindKey method, GotoKey method, GotoNearest method, TField component
Example
This example uses a label, a button named Search, and a button named Again on a form.
When the user clicks the Search button, the first file in the specified path is found, and
the name and the number of bytes in the file appear in the label's caption. Each time the
user clicks the Again button, the next matching file name and size is displayed in the
label:
var
SearchRec: TSearchRec;
procedure TForm1.SearchClick(Sender: TObject);
begin
FindFirst('c:\delphi\bin\*.*', faAnyFile, SearchRec);
Label1.Caption := SearchRec.Name + ' is ' + IntToStr(SearchRec.Size) +
' bytes in size';
end;
procedure TForm1.AgainClick(Sender: TObject);
begin
FindNext(SearchRec);
Label1.Caption := SearchRec.Name + ' is ' + IntToStr(SearchRec.Size) +
' bytes in size';
end;
See also
FindFirst function
FindText property
Applies to
TFindDialog, TReplaceDialog components
Declaration
property FindText: string;
The FindText property contains the string your application can search for if it uses the
Find dialog box.
You can specify a FindText value before the user displays the Find dialog box so that
when it appears, the FindText value appears in the Find What edit box. The user can
then either accept or change the FindText value before choosing the Find Next button in
the dialog box.
Example
The following OnFind event handler searches a memo component for the text specified
in the FindText property of a find dialog component. If found, the first occurrence of the
text in Memo1 is selected. The code uses the Pos function to compare strings, and stores
the number of characters to skip when determining the selection position in the
SkipChars variable. Because there is no handling of case, whole word, or search direction
in this algorithm, it is assumed that the Options property of FindDialog1 was set to
[frHideMatchCase, frHideWholeWord, frHideUpDown].
procedure TForm1.FindDialog1Find(Sender: TObject);
var
I, J, PosReturn, SkipChars: Integer;
begin
For I := 0 to Memo1.Lines.Count do
begin
PosReturn := Pos(FindDialog1.FindText,Memo1.Lines[I]);
if PosReturn <> 0 then {found!}
begin
Skipchars := 0;
for J := 0 to I - 1 do
Skipchars := Skipchars + Length(Memo1.Lines[J]);
SkipChars := SkipChars + (I*2);
SkipChars := SkipChars + PosReturn - 1;
Memo1.SetFocus;
Memo1.SelStart := SkipChars;
Memo1.SelLength := Length(FindDialog1.FindText);
end;
end;
end;
See also
ReplaceText property
First method
Applies to
TList object; TQuery, TStoredProc, TTable components
See also
IndexOf method, Last method
See also
Last method, MoveBy method, Next method, Prior method, SetRange method,
SetRangeStart method
FirstIndex property
Applies to
TTabSet component
Declaration
property FirstIndex: Integer;
Run-time only. The value of the FirstIndex property is the tab that appears in the leftmost
visible position in the tab set control. Any tabs with a lower value in the FirstIndex
property scroll to the left in the tab set control and don’t appear until the user scrolls the
tabs.
The default value of FirstIndex is 0 indicating that the tab with an index of 0 is in the
leftmost position. For example, if you have three tabs labeled First, Second, and Third
with TabIndex values of 0, 1, and 2, respectively, First appears first, by default, because it
has an index value of 0. If you want to shift the tabs so the Second or Third tab appears
leftmost in the tab set control, change the FirstIndex value to 1 or 2.
Example
This example uses a tab set control, a label, and a button on a form.
This code in an event handler creates 20 tabs labeled Tab 1 through Tab 20 when Form1
is created:
procedure TForm1.FormCreate(Sender: TObject);
var
I: Integer;
begin
for I := 0 to 19 do
TabSet11.Tabs.Add('Tab ' + IntToStr(I));
end;
Users can scroll through the tabs. When they click the button, the caption of the first tab
visible in the tab set control is displayed in the label control.
procedure TForm1.Button1Click(Sender: TObject);
var
I: Integer;
begin
Label1.Caption := IntToStr(TabSet11.FirstIndex);
end;
See also
TabIndex property, Tabs property
FixedColor property
Applies to
TDBGrid, TDrawGrid, TStringGrid components
Declaration
property FixedColor: TColor;
The value of the FixedColor property determines the color of nonscrolling or fixed
columns and rows within the grid. Refer to the Color property for a list of the possible
values for FixedColor.
The default color is clBtnFace, the color of the face of a button.
Example
This example uses a draw grid and a button on a form. When the user clicks the button,
the color of the nonscrolling (fixed) rows and columns of the draw grid changes color.
Declaration
property FixedCols: Integer;
The FixedCols property determines the number of nonscrolling columns within a grid.
The default value is 1. Nonscrolling columns remain fixed at the far left of the grid, even
when the user scrolls the other columns. Nonscrolling columns are useful for displaying
row titles that need to remain visible in the grid at all times.
Each grid must have a least one column that isn’t fixed. In other words, the value of the
FixedCols property must always be at least one less than the value of the ColCount
property, which contains the number of columns in the grid.
Example
This example uses a string grid and a button. When the user clicks the button, a message
dialog box appears informing the user that a fixed column number of 2 is
recommended. The dialog box also offers the user an opportunity to accept the
recommended number if the number of fixed columns isn’t already 2. If the user
chooses Yes, the number of fixed columns changes to 2.
procedure TForm1.Button1Click(Sender: TObject);
var
Check: Integer;
begin
if StringGrid1.FixedCols <> 2 then
begin
Check := MessageDlg('2 fixed columns are recommended! Change?',
mtWarning, mbYesNoCancel, 0);
if Check = IdYes then
StringGrid1.FixedCols := 2;
end;
end;
See also
FixedColor property, FixedRows property, LeftCol property
FixedRows property
Applies to
TDrawGrid, TStringGrid components
Declaration
property FixedRows: Integer;
The FixedRows property determines the number of nonscrolling rows within a grid. The
default value is 1. Nonscrolling rows remain fixed at top of the grid, even when the user
scrolls the other rows. Nonscrolling rows are useful for displaying column titles that
need to remain visible in the grid at all times.
Each grid must have a least one row that isn’t fixed. In other words, the value of the
FixedRows property must always be at least one less than the value of the RowCount
property, which contains the number of rows in the grid.
Example
This example uses a string grid and three radio buttons on a form. With the Object
Inspector, specify the following event handler for all OnClick events of the three radio
buttons. As the user selects different radio buttons, the number of fixed rows in the
string grid changes.
procedure TForm1.RadioButton1Click(Sender: TObject);
begin
if RadioButton1.Checked then
StringGrid1.FixedRows := 1
else if RadioButton2.Checked then
StringGrid1.FixedRows := 2
else if RadioButton3.Checked then
StringGrid1.FixedRows := 3;
end;
See also
FixedColor property, FixedCols property, TopRow property
The Precision parameter specifies the requested number of significant digits in the
+
result—the allowed range is 1..18. +
The Decimals parameter specifies the requested maximum number of digits to the left of
the decimal point in the result. +
Precision and Decimals together control how the result is rounded. To produce a result
that always has a given number of significant digits regardless of the magnitude of the +
number, specify 9999 for the Decimals parameter.
The result of the conversion is stored in the specified TFloatRec record as follows:
+
Field Value
F
Exponent Contains the magnitude of the number, i.e. the number of significant digits to the right of
the decimal point. The Exponent field is negative if the absolute value of the number is
less than one. If the number is a NAN (not-a-number), Exponent is set to -32768. If the
number is INF or -INF (positive or negative infinity), Exponent is set to 32767.
Negative True if the number is negative, False if the number is zero or positive.
Digits Contains up to 18 significant digits followed by a null terminator. The implied decimal
point (if any) is not stored in Digits. Trailing zeros are removed, and if the resulting
number is zero, NAN, or INF, Digits contains nothing but the null terminator.
The possible values of the Format parameter, and the meaning of each, are described
below.
Value Meaning
ffGeneral General number format. The value is converted to the shortest possible decimal string
using fixed or scientific format. Trailing zeros are removed from the resulting string, and a
decimal point appears only if necessary. The resulting string uses fixed point format if the
number of digits to the left of the decimal point in the value is less than or equal to the
specified precision, and if the value is greater than or equal to 0.00001. Otherwise the
resulting string uses scientific format, and the Digits parameter specifies the minimum
number of digits in the exponent (between 0 and 4).
ffExponent Scientific format. The value is converted to a string of the form "-d.ddd...E+dddd". The
resulting string starts with a minus sign if the number is negative, and one digit always
precedes the decimal point. The total number of digits in the resulting string (including
the one before the decimal point) is given by the Precision parameter. The "E" exponent
character in the resulting string is always followed by a plus or minus sign and up to four
digits. The Digits parameter specifies the minimum number of digits in the exponent
(between 0 and 4).
ffFixed Fixed point format. The value is converted to a string of the form "-ddd.ddd...". The
resulting string starts with a minus sign if the number is negative, and at least one digit
always precedes the decimal point. The number of digits after the decimal point is given
by the Digits parameter—it must be between 0 and 18. If the number of digits to the left of
the decimal point is greater than the specified precision, the resulting value will use
scientific format.
ffNumber Number format. The value is converted to a string of the form "-d,ddd,ddd.ddd...". The
ffNumber format corresponds to the ffFixed format, except that the resulting string contains
thousand separators taken from WIN.INI.
ffCurrency Currency format. The value is converted to a string that represents a currency amount.
The conversion is controlled by the CurrencyString, CurrencyFormat, NegCurrFormat,
ThousandSeparator, and DecimalSeparator global variables, all of which are initialized from
the Currency Format in the International section of the Windows Control Panel and
WIN.INI. The number of digits after the decimal point is given by the Digits parameter—it
must be between 0 and 18.
For all formats, the actual characters used as decimal and thousand separators are
obtained from the DecimalSeparator and ThousandSeparator global variables.
If the given value is a NAN (not-a-number), the resulting string is 'NAN'. If the given
value is positive infinity, the resulting string is 'INF'. If the given value is negative
infinity, the resulting string is '-INF'.
Declaration
procedure FloodFill(X, Y: Integer; Color: TColor; FillStyle: TFillStyle);
The FloodFill method fills an area of the screen surface using the current brush specified
by the Brush property. The FloodFill method begins at the point at coordinates (X, Y) and
continues in all directions to the color boundary.
The way in which the area is filled is determined by the FillStyle parameter. If FillStyle is
fsBorder, the area fills until a border of the color specified by the Color parameter is
encountered. If FillStyle is fsSurface, the area fills as long as the color specified by the
Color parameter is encountered. fsSurface fills are useful to fill an area with a
multicolored border.
Example
The following code floodfills from the center point of Form1’s client area until the color
black is encountered.
Form1.Canvas.FloodFill(ClientWidth/2, ClientHeight/2, clBlack, fsBorder);
See also
Ellipse method, FillRect method, Polygon method, Rectangle method
Example
var
f: TextFile;
begin
if OpenDialog1.Execute then
begin { open a text file }
AssignFile(f, OpenDialog1.FileName);
Append(f);
Writeln(f, 'I am appending some stuff to the end of the file.');
Flush(f); { ensures that the text was actually written to file }
CloseFile(f);
end;
end;
See also
Format function
Example
{ Set focus to first data-aware component associated with Field1 }
Field1.FocusControl;
FocusControl property
Applies to
TLabel component
Declaration
property FocusControl: TWinControl;
The FocusControl links the label control with another control on the form. If the Caption
of a label includes an accelerator key, the control specified as the value of the
FocusControl property becomes the focused control when the user uses the accelerator
key.
The caption of a label often identifies the purpose of another control on the form, or
directs the user to interact with it. For example, a label placed right above an edit box
might have the caption ’File Name’, indicating the user should type a file name in the
edit box. In this case, making that edit box the value of the label’s FocusControl property
gives the edit box the focus when the user presses Alt+F.
Example
This code displays a line of text in a label on the form and associates the label with an
edit box control. Note that the label caption includes an accelerator key. When the user
presses Alt+N, the edit box control receives the focus:
Label1.Caption := ‘&Name';
Label1.FocusControl := Edit1;
For this example, you need to place the label and edit box control close together to make
sure that users understand that they should enter text in the edit box.
See also
ShowAccelChar property, TabStop property
Focused method
Applies to
All windowed controls
Declaration
function Focused: Boolean;
The Focused method is used to determine whether a windowed control has the focus and
is therefore is the ActiveControl.
Example
This example uses an edit box and a memo on a form. When the user switches the focus
between the two controls, the control that currently has the focus becomes red:
type
TForm1 = class(TForm)
Edit1: TEdit;
Memo1: TMemo;
Button1: TButton;
procedure FormCreate(Sender: TObject);
private
{ Private declarations }
public
procedure ColorControl(Sender: TObject);
end;
var
Form1: TForm1;
implementation
{$R *.DFM}
procedure TForm1.ColorControl(Sender: TObject);
begin
if Edit1.Focused then
Edit1.Color := clRed
else
Edit1.Color := clWindow;
if Memo1.Focused then
Memo1.Color := clRed
Declaration
property Font: TFont;
The Font property is a font object that controls the attributes of text written on or in the
component or object or sent to the printer. To modify a font, you change the value of the
Color, Name, Size, or Style properties of the font object.
Example
This code changes color of text in a memo control to dark blue:
Memo1.Font.Color := clNavy;
See also
ParentFont property
Declaration
property Font: TFont;
The Font property is the font the Font dialog box returns when the user uses the Font
dialog box. Your application can then use this returned Font value for further
processing.
You can also specify a default font before displaying the Font dialog box; the font name
then appears selected in the Font combo box. Use the Object Inspector to specify a Font
property, or assign a value to Font before using the Execute method to display the dialog
box.
Example
This example uses a button, a Font dialog box, and a label on a form. When the user
clicks the button, the Font dialog box appears. If the user uses the dialog box to change
the font and chooses OK, the caption of the label changes to reflect the user’s font
selection.
procedure TForm1.Button1Click(Sender: TObject);
begin
FontDialog1.Font.Name := 'System';
FontDialog1.Font.Size := 10;
if FontDialog1.Execute then
Label1.Font := FontDialog1.Font;
end;
See also
Color property, Name property, Size property
Fonts property
Applies to
TPrinter object; TScreen component
Declaration
property Fonts: TStrings;
Run-time and read only. The Fonts property for the screen component returns a list of
fonts supported by the screen.
The Fonts property for a printer object holds a list of fonts supported by the printer. The
list contains TrueType fonts even if the printer doesn’t support them natively because
the Windows Graphics Device Interface (GDI) can draw TrueType fonts accurately
when a print job uses them.
Example
This code displays the fonts supported by the screen in a FontList list box when the user
clicks the ListFonts button:
procedure TForm1.ListFontsClick(Sender: TObject);
var
FontIndex: Integer;
begin
FontList.Clear;
FontList.Sorted := True;
FontList.Items := Screen.Fonts;
end;
Example
This example uses a label and a button on a form. When the user clicks the button, all the
directories along the specified path that don’t exist are created. The results are reported
in the caption of the label:
procedure TForm1.Button1Click(Sender: TObject);
var
Dir: string;
begin
Dir := 'C:\APPS\SALES\LOCAL';
ForceDirectories(Dir);
if DirectoryExists(Dir) then
Label1.Caption := Dir + ' was created'
end;
See also
DirectoryExists function, SelectDirectory function
Format strings
Format strings passed to the string formatting routines contain two types of objects—
plain characters and format specifiers. Plain characters are copied verbatim to the
resulting string. Format specifiers fetch arguments from the argument list and apply
formatting to them.
Format specifiers have the following form:
"%" [index ":"] ["-"] [width] ["." prec] type
A format specifier begins with a % character. After the % come the following, in this
order:
• An optional argument index specifier, [index ":"]
• An optional left justification indicator, ["-"]
• An optional width specifier, [width]
• An optional precision specifier, ["." prec]
• The conversion type character, type
The following table summarizes the possible values for type:
StrLFmt function
FormatChars property
Applies to
TDDEClientConv component
Declaration
property FormatChars: Boolean;
The FormatChars property determines if certain characters are filtered out of text data
transferred from a DDE server application. Some DDE server applications transfer
backspaces, linefeeds, carriage returns, and tabs with the text data. Sometimes, this can
cause incorrect spacing, line breaks, or characters in the DDE client data. If this is the
case, the characters should be filtered. The default value of FormatChars is False.
If False, all text characters of the linked data from the DDE server appear in the linked
data in the DDE client. If True, ASCII characters 8 (backspace), 9 (tab), 10 (linefeed), and
13 (carriage return) are filtered out and won’t appear in the DDE client data.
Example
The following code formats characters if the DDE service name is “SuperWrd”.
if DDEClientConv.DDEService = ’SuperWrd’ then
DDEClientConv.FormatChars := True;
FormatCount property
Applies to
TClipboard object
See also
Assign method, AsText property, Clipboard variable, GetComponent method, HasFormat
method, SetComponent method
Specifier Displays
c Displays the date using the format given by the ShortDateFormat global variable, followed
by the time using the format given by the LongTimeFormat global variable. The time is not
displayed if the fractional part of the DateTime value is zero.
d Displays the day as a number without a leading zero (1-31).
dd Displays the day as a number with a leading zero (01-31).
ddd Displays the day as an abbreviation (Sun-Sat) using the strings given by the
ShortDayNames global variable.
dddd Displays the day as a full name (Sunday-Saturday) using the strings given by the
LongDayNames global variable.
ddddd Displays the date using the format given by the ShortDateFormat global variable.
dddddd Displays the date using the format given by the LongDateFormat global variable.
m Displays the month as a number without a leading zero (1-12). If the m specifier
immediately follows an h or hh specifier, the minute rather than the month is displayed.
mm Displays the month as a number with a leading zero (01-12). If the mm specifier
immediately follows an h or hh specifier, the minute rather than the month is displayed.
mmm Displays the month as an abbreviation (Jan-Dec) using the strings given by the
ShortMonthNames global variable.
Specifier Displays
mmmm Displays the month as a full name (January-December) using the strings given by the
LongMonthNames global variable.
yy Displays the year as a two-digit number (00-99).
yyyy Displays the year as a four-digit number (0000-9999).
h Displays the hour without a leading zero (0-23).
hh Displays the hour with a leading zero (00-23).
n Displays the minute without a leading zero (0-59).
nn Displays the minute with a leading zero (00-59).
s Displays the second without a leading zero (0-59).
ss Displays the second with a leading zero (00-59).
t Displays the time using the format given by the ShortTimeFormat global variable.
tt Displays the time using the format given by the LongTimeFormat global variable.
am/pm Uses the 12-hour clock for the preceding h or hh specifier, and displays 'am' for any hour
before noon, and 'pm' for any hour after noon. The am/pm specifier can use lower, upper,
or mixed case, and the result is displayed accordingly.
a/p Uses the 12-hour clock for the preceding h or hh specifier, and displays 'a' for any hour
before noon, and 'p' for any hour after noon. The a/p specifier can use lower, upper, or
mixed case, and the result is displayed accordingly.
ampm Uses the 12-hour clock for the preceding h or hh specifier, and displays the contents of the
TimeAMString global variable for any hour before noon, and the contents of the
TimePMString global variable for any hour after noon.
/ Displays the date separator character given by the DateSeparator global variable.
: Displays the time separator character given by the TimeSeparator global variable.
'xx'/"xx" Characters enclosed in single or double quotes are displayed as-is, and do not affect
formatting.
Format specifiers may be written in upper case as well as in lower case letters—both
produce the same result.
If the string given by the Format parameter is empty, the date and time value is
formatted as if a 'c' format specifier had been given.
Example
The following example assigns 'The meeting is on Wednesday, February 15, 1995 at
10:30 AM' to the string variable S.
S := FormatDateTime('"The meeting is on" dddd, mmmm d, yyyy, ' +
'"at" hh:mm AM/PM', StrToDateTime('2/15/95 10:30am'));
FormatFloat formats the floating-point value given by Value using the format string
+
given by Format. The following format specifiers are supported in the format string: +
Specifier
0
Represents
Digit placeholder. If the value being formatted has a digit in the position where the '0'
+
appears in the format string, then that digit is copied to the output string. Otherwise, a '0'
is stored in that position in the output string. +
# Digit placeholder. If the value being formatted has a digit in the position where the '#'
appears in the format string, then that digit is copied to the output string. Otherwise,
nothing is stored in that position in the output string.
+
. Decimal point. The first '.' character in the format string determines the location of the
decimal separator in the formatted value; any additional '.' characters are ignored. The F
actual character used as a the decimal separator in the output string is determined by the
DecimalSeparator global variable. The default value of DecimalSeparator is specified in the
Number Format of the International section in the Windows Control Panel.
, Thousand separator. If the format string contains one or more ',' characters, the output
will have thousand separators inserted between each group of three digits to the left of the
decimal point. The placement and number of ',' characters in the format string does not
affect the output, except to indicate that thousand separators are wanted. The actual
character used as a the thousand separator in the output is determined by the
ThousandSeparator global variable. The default value of ThousandSeparator is specified in
the Number Format of the International section in the Windows Control Panel.
E+ Scientific notation. If any of the strings 'E+', 'E-', 'e+', or 'e-' are contained in the format
string, the number is formatted using scientific notation. A group of up to four '0'
characters can immediately follow the 'E+', 'E-', 'e+', or 'e-' to determine the minimum
number of digits in the exponent. The 'E+' and 'e+' formats cause a plus sign to be output
for positive exponents and a minus sign to be output for negative exponents. The 'E-' and
'e-' formats output a sign character only for negative exponents.
'xx'/"xx" Characters enclosed in single or double quotes are output as-is, and do not affect
formatting.
; Separates sections for positive, negative, and zero numbers in the format string.
The locations of the leftmost '0' before the decimal point in the format string and the
rightmost '0' after the decimal point in the format string determine the range of digits
that are always present in the output string.
The number being formatted is always rounded to as many decimal places as there are
digit placeholders ('0' or '#') to the right of the decimal point. If the format string contains
no decimal point, the value being formatted is rounded to the nearest whole number.
If the number being formatted has more digits to the left of the decimal separator than
there are digit placeholders to the left of the '.' character in the format string, the extra
digits are output before the first digit placeholder.
To allow different formats for positive, negative, and zero values, the format string can
contain between one and three sections separated by semicolons.
• One section: The format string applies to all values.
• Two sections: The first section applies to positive values and zeros, and the second
section applies to negative values.
• Three sections: The first section applies to positive values, the second applies to
negative values, and the third applies to zeros.
If the section for negative values or the section for zero values is empty, that is if there is
nothing between the semicolons that delimit the section, the section for positive values
is used instead.
If the section for positive values is empty, or if the entire format string is empty, the
value is formatted using general floating-point formatting with 15 significant digits,
corresponding to a call to FloatToStrF with the ffGeneral format. General floating-point
formatting is also used if the value has more than 18 digits to the left of the decimal
point and the format string does not specify scientific notation.
Example
The following table shows some sample formats and the results produced when the
formats are applied to different values:
Formats property
Applies to
TClipboard object
Declaration
property Formats[Index: Integer]: Word;
Run-time and read only. The Formats property array contains a list of all the formats the
Clipboard contains. Usually when an application copies or cuts something to the
Clipboard, it places it there in multiple formats.
Your application can place items of a particular format on the Clipboard and retrieve
items with a particular format from the Clipboard if the format is in the Formats array.
You can find out if a particular format is available on the Clipboard with the HasFormat
method.
The Index parameter of the Formats property lets you access a format by its position in
the array.
FormCount property
Applies to
TScreen component
Declaration
property FormCount: Integer;
Run-time and read only. The FormCount property value contains the number of forms
displayed on the screen.
Example
The following code adds the name of all forms on the screen to ListBox1 when Button1 is
clicked.
procedure TForm1.Button1Click(Sender: TObject);
var
I: Integer;
begin
For I := 0 to Screen.FormCount-1 do
ListBox1.Items.Add(Screen.Forms[I].Name);
end;
See also
Forms property, Screen variable
Forms property
Applies to
TScreen component
Declaration
property Forms[Index: Integer]: TForm;
Description
Run-time and read only. The Forms property lets you access a form on the screen by
specifying its position in the list of forms kept by the TScreen component using its Index
value. The first form has an index value of 0, the second has an index value of 1, and so
on.
Example
The following code adds the name of all forms on the screen to ListBox1 when Button1 is
clicked.
procedure TForm1.Button1Click(Sender: TObject);
var
I: Integer;
begin
For I := 0 to Screen.FormCount-1 do
ListBox1.Items.Add(Screen.Forms[I].Name);
end;
See also
FormCount property, Screen variable
FormStyle property
Applies to
TForm component
Declaration
property FormStyle: TFormStyle;
The FormStyle property determines the style of the form. These are the possible values
and their meanings:
Value Meaning
fsNormal The form is neither an MDI parent window nor an MDI child window.
fsMDIChild The form is an MDI child window.
fsMDIForm The form is an MDI parent window.
fsStayOnTop This form remains on top of other forms in the project, except any others that also have
FormStyle set to fsStayOnTop.
forms contained within the MDI parent form. You must use the Object Inspector to set
+
the child form’s Visible property to True or your child form won’t appear. You can have
as many child forms as you like.
+
Example
+
This example ensures the main form of the application is an MDI parent form: +
+
procedure TForm1.FormCreate(Sender: TObject);
begin
if FormStyle <> fsMDIForm then
FormStyle := fsMDIForm;
if FormStyle = fsMDIForm then F
Edit1.Text := 'MDI form'
else
Edit1.Text := 'Not an MDI form'; {This line never runs}
end;
See also
CreateForm method, MainForm property, Visible property
Example
var
R: Real;
begin
R := Frac(123.456); { 0.456 }
R := Frac(–123.456); { –0.456 }
end;
See also
Int function
FrameRect method
Applies to
TCanvas object
Declaration
procedure FrameRect(const Rect: TRect);
The FrameRect method draws a rectangle using the Brush of the canvas to draw the
border. FrameRect does not fill the interior of the rectangle with the Brush pattern.
Example
The following code displays the text “Hello, world!” in a rectangle defined by the
coordinates (10, 10) and (100, 100). After displaying the text with the TextRect method,
the code draws a black, vertical line frame around the rectangle.
var
TheRect: TRect;
begin
Form1.Canvas.Brush.Color := clBlack;
Form1.Canvas.Brush.Style := bsVertical;
TheRect.Top := 10;
TheRect.Left := 10;
TheRect.Bottom := 100;
TheRect.Right := 100;
Form1.Canvas.TextRect(TheRect,10,10,'Hello, world!');
Form1.Canvas.FrameRect(TheRect);
end;
See also
Brush property, Rect function, TextRect method
Frames property
Applies to
TMediaPlayer component
Declaration
property Frames: Longint;
Run-time-only. The Frames property specifies the number of frames the Step method
steps forward or the Back method steps backward.
Frames defaults to ten percent of the length of the currently loaded medium, which is
specified by the Length property.
Note The definition of frame varies by multimedia device. For display media, a frame is one
still image.
Example
The following code frees an object called MyObject:
MyObject.Free;
See also
Destroy method, Release method
FreeBookmark method
Applies to
TTable, TQuery, TStoredProc components
Declaration
procedure FreeBookmark(Bookmark: TBookmark);
Use the FreeBookmark method in combination with the GetBookmark and GotoBookmark
methods. FreeBookmark releases the system resources reserved during a call to
GetBookmark.
Example
var MyBookmark: TBookmark;
...
with Table1 do
begin
{ Save the current record position in MyBookmark }
MyBookmark := GetBookmark;
... { Other code here }
{ Return to the record associated with MyBookmark }
GotoBookmark(MyBookmark);
{ Release the resources for MyBookmark }
FreeBookmark(MyBookmark);
end;
See also
Dispose procedure, GetMem procedure, New procedure
FromPage property
Applies to
TPrintDialog component
Declaration
property FromPage: Integer;
The value of the FromPage property determines on which page the print job begins. The
default value is 0.
Example
This example uses a Print dialog box on a form. These lines set up the Print dialog box so
that when it appears, the default values of 1 and 1 are the default starting and ending
values for the Pages From and To edit boxes.
PrintDialog1.Options := [poPageNums];
PrintDialog1.FromPage := 1;
PrintDialog1.ToPage := 1;
See also
ToPage property
FullCollapse method
Applies to
TOutline component
Declaration
procedure FullCollapse;
FullCollapse collapses all the items within an outline. When an item is collapsed, its
Expanded property is set to False, its subitems are hidden, and the closed or plus pictures
might be displayed, depending on the outline style specified in the OutlineStyle
property.
Example
The following code collapses the outline if the selected item is visible.
if Outline[Outline1.SelectedItem].IsVisible then
Outline1.FullCollapse;
See also
Collapse method, Expand method, FullExpand method, OnCollapse event, PictureClosed
property, PicturePlus property
FullExpand method
Applies to
TOutlineNode object; TOutline component
Declaration
procedure FullExpand;
FullExpand expands the items within an outline. If the FullExpand method belongs to a
TOutline component, all items in the outline are expanded. If the FullExpand method
belongs to a TOutlineNode object, only the items on the same branch as the outline node
are expanded. This means that all subitems are expanded, and all parents up to the top
item on level 1 (specified by the TopItem property) are expanded. No items on other
branches (with different level 1 parents) are expanded.
When an item is expanded, its Expanded property is set to True, its subitems are
displayed, and the open or minus pictures might be displayed, depending on the
outline style specified in the OutlineStyle property.
Declaration
property FullPath: string;
Run-time and read only. The FullPath property specifies the path of outline items from
the top item on level 1 to the item contained by the TOutlineNode. The path consists of
the values of the Text properties of the outline items separated by the string specified in
the ItemSeparator property of the TOutline component.
Example
The following code displays the full path of the selected outline item in Label1:
Label1.Caption := Outline1.Items[Outline1.SelectedItem].FullPath;
See also
Items property, SelectedItem property
GetAliasNames method
Applies to
TSession component
Declaration
procedure GetAliasNames(List: TStrings);
The GetAliasNames method clears the parameter List and adds to it the names of all
defined BDE aliases. Application-specific aliases are not included.
Example
Session.GetAliasNames(MyStringList);
See also
GetDataBaseNames method, Session variable
GetAliasParams method
Applies to
TSession component
Declaration
procedure GetAliasParams(const AliasName: string; List: TStrings);
The GetAliasParams method clears List and adds to it the parameters associated with the
BDE alias passed in AliasName.
Example
Session.GetAliasParams(MyStringList);
See also
Session variable
GetAsHandle method
Applies to
TClipboard object
Declaration
function GetAsHandle (Format: Word): THandle;
The GetAsHandle method returns the data from the Clipboard in a Windows handle for
the format specified in the Format parameter. See the Windows API Help file for
information about the available formats.
Your application doesn’t own the handle, so it should copy the data before using it.
Example
The following code locks the memory for text on the Clipboard, then converts the text to
a Pascal-style string.
var
TheClipboard: TClipboard;
MyHandle: THandle;
TextPtr: PChar;
MyString: string;
begin
MyHandle := TheClipboard.GetAsHandle(CF_TEXT);
Example
var MyBookmark: TBookmark;
...
with Table1 do
begin
{ Save the current record position in MyBookmark }
MyBookmark := GetBookmark;
... { Other code here }
{ Return to the record associated with MyBookmark }
GotoBookmark(MyBookmark);
{ Release the resources for MyBookmark }
FreeBookmark(MyBookmark);
end;
GetComponent method
Applies to
TClipboard object
Declaration
function GetComponent(Owner, Parent: TComponent): TComponent;
The GetComponent method retrieves a component from the Clipboard and places it
according to the value of the Owner and Parent parameters. With Owner, specify the
component that becomes the owner of the retrieved component—usually this is a form.
With Parent, specify the component that becomes the parent of the component. Both
Owner and Parent can be nil.
Example
This example uses a button and a group box on a form. When the user clicks the button,
the button is copied to the Clipboard and then retrieved from the Clipboard and placed
in the new parent of the button, the group box. The name of the original button is
changed to an empty string to avoid having two components with the same name at the
same time.
implementation
uses Clipbrd;
{$R *.DFM}
procedure TForm1.Button1Click(Sender: TObject);
begin
Clipboard.SetComponent(Button1); { copies button to the Clipboard }
Button1.Name := ''; { prevents having two components with the same name }
Clipboard.GetComponent(Self, GroupBox1); { retrieves button from Clipboard and }
end; { places it in the group box }
initialization
RegisterClasses([TButton]); { registers the TButton class }
end.
See also
AsText property, Owner property, Parent property, SetComponent method
GetData method
Applies to
TParam object; TBCDField, TBlobField, TBooleanField, TBytesField, TCurrencyField,
TDateField, TDateTimeField, TFloatField, TGraphicField, TIntegerField, TMemoField,
TSmallintField, TStringField, TTimeField, TVarBytesField, TWordField components
For fields
Declaration
function GetData(Buffer: Pointer): Boolean;
GetData is the method used to obtain “raw” data from the field. Unlike the AsString,
+
DisplayText, and Text properties, GetData performs no translation or interpretation of the
data. Buffer must have sufficient space allocated for the data. Use the DataSize property
+
to determine the space required. If the data is NULL, GetData returns False and no data
is transferred to Buffer. Otherwise, it returns True.
+
Example
+
{ Retrieve the “raw” data from Field1 }
with Field1 do
+
begin
{ Allocate space } +
GetMem(Buffer, DataSize);
if not Field1.GetData(Buffer) then
MessageDlg(FieldName + ' is NULL’, mtInformation, [mbOK], 0)
G
else { Do something with the data };
{ Free the space }
FreeMem(Buffer, DataSize);
end;
Example
var Buffer: Pointer;
{ Allocate enough space to hold the CustNo data }
GetMem(Buffer, Query1.ParamByName(‘CustNo’).GetDataSize);
{ Retrieve the data }
Query1.ParamByName(‘CustNo’).GetData(Buffer);
See also
SetData method
GetDatabaseNames method
Applies to
TSession component
Declaration
procedure GetDatabaseNames(List: TStrings);
The GetDatabaseNames method clears List and adds to it the names of all BDE aliases and
application-specific aliases.
Example
Session.GetDatabaseNames(MyStringList);
See also
GetAliasNames method, Session variable
GetDataItem method
Applies to
TOutline component
Declaration
function GetDataItem(Value: Pointer): Longint;
The GetDataItem method returns the Index value of the first outline item that contains the
data specified in the Value parameter in its Data property. Use GetDataItem when you
have a pointer to data and you want to know which outline item contains the data.
Example
The following code displays the Text of the outline item that points to the variable P3 in
its Data property. The text is displayed in a label.
Label1.Caption := Outline1.Items[GetDataItem(p3)].Text;
See also
GetItem method, GetTextItem method
GetDataSize method
Applies to
TParam object
Declaration
function GetDataSize: Word;
The GetDataSize method returns the number of bytes required to hold the parameter’s
value. Use GetDataSize in conjunction with the GetData method to allocate memory for
the parameter’s data.
Example
var Buffer: Pointer;
Example
var
s : string;
begin
GetDir(0,s); { 0 = Current drive }
MessageDlg('Current drive and directory: ' + s, mtInformation, [mbOk] , 0);
end;
See also
ChDir function, MkDir procedure, RmDir procedure
GetDriverNames method
Applies to
TSession component
Declaration
procedure GetDriverNames(List: TStrings);
The GetDriverNames method clears List and adds to it the names of all BDE drivers
currently installed. This will not include ‘PARADOX’ or ‘DBASE’, since these databases
are handled by the driver named ‘STANDARD’.
Example
Session.GetDriverNames(MyStringList);
See also
Session variable
GetDriverParams method
Applies to
TSession component
Declaration
procedure GetDriverParams(const DriverName: string; List: TStrings);
The GetDriverParams method clears List and adds to it the default parameters for the
driver named in DriverName parameter. The driver named ‘STANDARD’ (used for
Paradox and dBASE tables) has only one parameter, ‘PATH=’. SQL drivers will have
varying parameters.
Example
Session.GetDriverParams(MyStringList);
See also
Session variable
GetFieldNames method
Applies to
TTable, TQuery, TStoredProc components
Declaration
procedure GetFieldNames(List: TStrings);
The GetFieldNames method clears the TStrings argument, List, and then adds the name of
each field in the dataset to it.
Example
var FieldNames: TStringList;
...
{ Initialize FieldNames to hold the names }
FieldNames := TStringList.Create;
{ Get the names }
Table1.GetFieldNames(FieldNames);
Example
The following code expands the selected outline item if it has children and then selects
the first child.
with Outline1 do
if Items[SelectedItem].HasItems then
begin
Items[SelectedItem].Expanded := True;
SelectedItem := Items[Items[SelectedItem].GetFirstChild];
end;
See also
GetLastChild method, GetNextChild method, GetPrevChild method
GetFormImage method
Applies to
TForm component
Declaration
function GetFormImage: TBitmap;
The GetFormImage returns a bitmap of the form as it appears when printed.
Example
This example uses an image, a button, and a shape component on a form. When the user
clicks the button, an image of the form is stored in the FormImage variable and copied to
the Clipboard. Then image of the form in then copied back to the image component,
producing an interesting result, especially if the button is clicked multiple times.
procedure TForm1.Button1Click(Sender: TObject);
var
FormImage: TBitmap;
begin
FormImage := GetFormImage;
Clipboard.Assign(FormImage);
Image1.Picture.Assign(Clipboard);
end;
procedure TForm1.FormCreate(Sender: TObject);
begin
Shape1.Shape := stEllipse;
Shape1.Brush.Color := clLime;
Image1.Stretch := True;
end;
See also
PrintScale property
GetHelpContext method
Applies to
TMainMenu component
Declaration
function GetHelpContext(Value: Word; ByCommand: Boolean): THelpContext;
The GetHelpContext method returns a help context number.
See also
HelpContext property, HelpContext method, HelpJump method, OnHelp event
GetIndexForPage method
Applies to
TTabbedNotebook component
See also
SetTabFocus method
GetIndexNames method
Applies to
TTable component
Declaration
procedure GetIndexNames(List: TStrings);
The GetIndexNames method adds the names of all available indexes for the TTable to the
List parameter.
Example
var
MyList: TStringList;
...
MyList := TStringList.Create;
Table1.GetIndexNames(MyList);
{ Do something with the names }
MyList.Free;
See also
IndexName property
GetItem method
Applies to
TOutline component
Declaration
function GetItem(X, Y: Integer): Longint;
The GetItem method returns the Index value of the outline item that resides at the pixel
coordinates (X, Y). Use GetItem when you want to know which outline item is in a
specific screen location.
Example
The following code makes the item at screen coordinates (34,100) the selected item.
Outline1.SelectedItem := Outline1.GetItem(34,100);
See also
GetDataItem method, GetTextItem method
GetItemPath method
Applies to
TDirectoryListBox component
Declaration
function GetItemPath(Index : Integer): string;
The GetItemPath method returns as a string the path of a directory in a directory list box.
Specify the directory with the Index value using the first directory in the list that has an
index value of 0.
Example
This example uses a directory list box, a button, and a label on a form. When the user
selects a directory in the directory list box and clicks the button, the selected directory
opens, and the path of the second directory displayed in the list box appears as the
caption of the label.
procedure TForm1.Button1Click(Sender: TObject);
begin
DirectoryListBox1.OpenCurrent;
Example
The following code expands the selected outline item if it has children and then selects
the last child.
with Outline1 do
if Items[SelectedItem].HasItems then
begin
Items[SelectedItem].Expanded := True;
SelectedItem := Items[Items[SelectedItem].GetLastChild];
end;
See also
GetFirstChild method, GetNextChild method, GetPrevChild method
Example
This code assigns a two-part string as to the Hint property of an edit box and then
displays the “long” or second part of the string as the text of the edit box:
procedure TForm1.BitBtn1Click(Sender: TObject);
begin
Edit1.Hint := 'Name|Enter full name';
Edit1.Text := GetLongHint(Edit1.Hint);
end;
See also
GetShortHint function, OnHint event, ShowHint property
Example
type
TFriendRec = record
Name: string[30];
Age : Byte;
end;
var
p: pointer;
begin
if MaxAvail < SizeOf(TFriendRec) then
MessageDlg('Not enough memory', mtWarning, [mbOk], 0);
else
begin
{ Allocate memory on heap }
GetMem(p, SizeOf(TFriendRec));
{ ...}
{ ...Use the memory... }
{ ...}
{ then free it when done }
FreeMem(p, SizeOf(TFriendRec));
end;
end;
Example
The following code selects the next sibling of the selected item.
with Outline1 do
SelectedItem := Items[SelectedItem].GetNextChild(SelectedItem);
See also
GetFirstChild method, GetLastChild method, GetPrevChild method
Example
The following code shows the form that contains Button2:
GetParentForm(Button2).Show;
See also
ValidParentForm function
GetPassword method
Applies to
TSession component
Declaration
function GetPassword: Boolean;
The GetPassword method invokes the OnPassword event (if any) or displays the default
password dialog box. It then returns True if the user chose the OK button and False if the
user chose the Cancel button.
Example
Session.GetPassword;
See also
Session variable
GetPrevChild method
Applies to
TOutlineNode object
Declaration
function GetPrevChild(Value: Longint): Longint;
The GetPrevChild method returns the Index value of the previous outline item that shares
the same parent item as the item that has an Index value equal to the Value parameter.
This is useful when the previous sibling has subitems, thus its index is not simply one
less than Value. If the item indexed by Value has no previous sibling, GetPrevChild
returns -1.
Example
The following code tests to determine if the selected item has a previous sibling. The
results are displayed in a label.
with Outline1 do
if (Items[SelectedItem].GetPrevChild > -1) then
Label1.Caption := ’Has a prior sibling’
else
Label1.Caption := ’Has no prior sibling’;
See also
GetFirstChild method, GetLastChild method, GetNextChild method
GetResults method
Applies to
TParam object
Declaration
procedure GetResults;
You only need to call this method with a Sybase stored procedure that returns a result
set. GetResults returns the output parameter values from the stored procedure. Usually,
TStoredProc does this automatically, but Sybase stored procedures do not return the
values until the cursor reaches the end of the result set, so you must call GetResults
explicitly.
Example
StoredProc1.Open
while not EOF do
begin
StoredProc1.Next;
{Do Something}
end;
StoredProc1.GetResults;
Edit1.Text := StoredProc1.ParamByName(‘Output’);
GetSelTextBuf method
Applies to
TDBEdit, TDBMemo, TEdit, TMaskEdit, TMemo components
Declaration
function GetSelTextBuf(Buffer: PChar; BufSize: Integer): Integer;
The GetSelTextBuf method copies the selected text from the edit box or memo control
into the buffer pointed to by Buffer, up to a maximum of BufSize characters, and returns
the number of characters copied.
You should need to use the GetSelTextBuf method only if you are working with strings
longer than 255 characters. Because an Object Pascal style string has a limit of 255
characters, such properties as Text for an edit box, Items for a list box, and Lines for a
memo control do not allow you to work with strings longer than 255 characters.
GetSelTextBuf and the corresponding SetSelTextBuf methods use null-terminated strings
that can be up to 64K in length.
Example
procedure TForm1.Button1Click(Sender: TObject);
var
Buffer: PChar;
Size: Integer;
begin
Size := Edit1.SelLength; {Get length of selected text in Edit1}
Inc(Size); {Add room for null character}
GetMem(Buffer, Size); {Creates Buffer dynamic variable}
Edit1.GetSelTextBuf(Buffer,Size); {Puts Edit1.Text into Buffer}
Edit2.Text := StrPas(Buffer); {Converts string in Buffer into Pascal-style string}
FreeMem(Buffer, Size); {Frees memory allocated to Buffer}
end;
See also
GetLongHint function, OnHint event, ShowHint property
GetStoredProcNames method
Applies to
TSession component
Declaration
procedure GetStoredProcNames(const DatabaseName: string; List: TStrings);
GetStoredProcNames returns a list of all stored procedures defined for the specified SQL
database. This method is not valid for Paradox or dBASE databases.
Example
Session.GetStoredProcNames(‘IB_EMPLOYEE’, MyStringList);
See also
Session variable
GetTableNames method
Applies to
TSession component
Declaration
procedure GetTableNames(const DatabaseName, Pattern: string;
Extensions, SystemTables: Boolean; List: TStrings);
The GetTableNames method clears List and then adds to it the names of all the tables in
the database referenced by DatabaseName. The Pattern parameter will limit the table
names to those matching Pattern.
For SQL servers, set SystemTables to True to obtain system tables in addition to user
tables. For desktop (non-SQL) databases, set Extensions to True to include file-name
extensions in the table names.
Example
Session.GetTableNames(‘DBDEMOS‘, False, False, MyStringList);
See also
Session variable
GetText method
Applies to
TStrings, TStringList objects
Declaration
function GetText: PChar;
The GetText method returns a string list as a null-terminated string. GetText is useful
when working with components that contain blocks of text made up of more than one
string. For example, a memo component (TMemo) can contain multiple strings. When
you want to return the entire list of strings in a memo component all at once, use the
GetText method.
Example
The following code returns the text in the items of an outline to one variable called
MyVar.
MyVar := Outline1.Lines.GetText;
See also
SetText method
Example
This example copies the text in an edit box into a null-terminated string, and puts this
string in another edit box when the user clicks the button on the form.
procedure TForm1.Button1Click(Sender: TObject);
var
Buffer: PChar;
Size: Byte;
begin
Size := Edit1.GetTextLen; {Get length of string in Edit1}
Inc(Size); {Add room for null character}
GetMem(Buffer, Size); {Creates Buffer dynamic variable}
Edit1.GetTextBuf(Buffer,Size); {Puts Edit1.Text into Buffer}
Edit2.Text := StrPas(Buffer); {Converts Buffer to a Pascal-style string]
FreeMem(Buffer, Size); {Frees memory allocated to Buffer}
end;
See also
GetSelTextBuf method, SetTextBuf method
GetTextItem method
Applies to
TOutline component
Declaration
function GetTextItem(Value: string): Longint;
The GetTextItem method returns the Index value of the first outline item that contains the
string specified in the Value parameter in its Text property. Use GetTextItem when you
want to know which outline item is identified by a string.
Example
The following code returns the index of the outline item that contains the text ’Perry’ to
a variable called PerryIndex.
PerryIndex := Outline1.GetTextItem(’Perry’);
See also
GetDataItem method, GetItem method
GetTextLen method
Applies to
All controls
Declaration
function GetTextLen: Integer;
The GetTextLen method returns the length of the control’s text. The most common use of
GetTextLen is to find the size needed for a text buffer in the GetTextBuf method.
Example
This example uses two edit boxes and a button on a form. When the user clicks the
button, the length of the text in the Edit1 is displayed in Edit2.
procedure TForm1.Button1Click(Sender: TObject);
var
Size: Integer;
begin
Size := Edit1.GetTextLen;
Edit2.Text := ('Edit1 has ' + IntToStr(Size) + 'characters in it');
end;
See also
GetTextBuf method
Glyph property
Applies to
TBitBtn, TSpeedButton controls
If only one image is present, Delphi attempts to represent the other states by altering the
image slightly for the different states, although the stay down state is always the same as
the up state. If you aren’t satisfied with the results, you can provide one or more
additional images in the bitmap.
If you have multiple images in a bitmap, you must specify the number of images that
are in the bitmap with the NumGlyphs property. All images must be the same size and
next to each other in a horizontal row.
Example
This example uses a bitmap button on a form. When the application runs and the form is
created, a bitmap is placed on the bitmap button.
procedure TForm1.FormCreate(Sender: TObject);
begin
BitBtn1.Glyph.LoadFromFile('TARTAN.BMP');
end;
These lines of code load a four-image bitmap into the Glyph property of a speed button,
and specify the appropriate value for the NumGlyphs property:
SpeedButton1.Glyph.LoadFromFile(‘MYBITMAP.BMP’);
SpeedButton1.NumGlyphs := 4;
See also
Kind property, Layout property, Margin property, ModalResult property, NumGlyphs
property, Spacing property, TBitmap object
GotoBookmark method
Applies to
TTable, TQuery, TStoredProc components
Declaration
procedure GotoBookmark(Bookmark: TBookmark);
The GotoBookmark method moves the cursor to the record corresponding to the
bookmark obtained through a call to GetBookmark. While you must eventually call the
FreeBookmark method to release the resources reserved during the call to GetBookmark,
you are free to make as many calls to GotoBookmark as you wish before calling
FreeBookmark. If the Bookmark parameter is nil, GotoBookmark does nothing.
Example
var MyBookmark: TBookmark;
...
with Table1 do
begin
{ Save the current record position in MyBookmark }
MyBookmark := GetBookMark;
... { Other code here }
{ Return to the record associated with MyBookmark }
GotoBookMark(MyBookMark);
{ Release the resources for MyBookmark }
FreeBookmark(MyBookmark);
end;
GotoCurrent method
Applies to
TTable component
Declaration
procedure GotoCurrent(Table: TTable);
Use the GotoCurrent method to synchronize the positions of two TTable components that
use the same database table. GotoCurrent changes the position of the table to match that
of the Table parameter.
Note Both tables must have the same DatabaseName and TableName or a “table mismatch”
exception will be raised.
Example
Table1.GotoCurrent(Table2);
Example
with Table1 do
begin
EditKey;
FieldByName(‘CustNo’).AsFloat := 610;
GotoKey;
end;
See also
FindKey method
GotoNearest method
Applies to
TTable component
Declaration
procedure GotoNearest;
The GotoNearest method is used with the EditKey or SetKey method to move to a record
in the dataset whose index fields are greater than or equal to the IndexFields property.
Call SetKey first to put the TTable in SetKey state, modify the fields of the key, and finally
call GotoNearest to perform the move.
The KeyExclusive property indicates whether a search will position the cursor on or after
the specified record being searched for.
Note You do not have to assign a value for each field in the index key. Any unassigned field
will use a NULL value.
The search begins at the first record in the table, not at the current cursor position.
Example
with Table1 do
begin
SetKey;
FieldByName(‘State’).AsString := ‘CA‘;
FieldByName(‘City’).AsString := ‘Santa‘;
GotoNearest;
end;
See also
GotoKey method, KeyFieldCount property, SetKey method
Example
uses WinCrt;
var
C: PChar;
begin
GotoXY(10,10);
Writeln('Hello');
end;
See also
CursorTo procedure, WhereX function, WhereY function
Graphic property
Applies to
TPicture object
Example
The following code tests to determine if the graphic in Picture1 is an icon. If so, the
minimized icon of Form1 is set to the graphic.
if GraphicExtension(Picture1.Graphic)=’.ICO’ then
Form1.Icon := Picture1.Graphic;
See also
GraphicFilter function
The GraphicFilter function returns a filter string compatible with the Filter property value
of an Open or Save dialog box. The GraphicClass parameter can be one of these values:
TBitmap, TGraphic, TIcon, or TMetafile. These are the strings that are returned for each
class:
Example
This code displays an Open dialog box with the TBitmap filter string in the List Files of
Type combo box:
OpenDialog1.DefaultExt := GraphicExtension(TBitmap);
OpenDialog1.Filter := GraphicFilter(TBitmap);
if OpenDialog1.Execute then
...
See also
GraphicExtension function, TOpenDialog component, TSaveDialog component
GridHeight property
Applies to
TDrawGrid, TStringGrid components
Declaration
property GridHeight: Integer;
Run-time and read only. The GridHeight property is the height of the grid in pixels. If the
grid is too tall to be fully displayed causing the user to scroll to see its entire contents, the
value of GridHeight is the same as the ClientHeight property value for the grid.
Example
This example uses a string grid and a label on a form. The height of the grid appears in
the caption of the label.
procedure TForm1.FormCreate(Sender: TObject);
var
ARow, ACol: Integer;
begin
with StringGrid1 do
begin
for ARow := 1 to RowCount - 1 do
Declaration
property GridLineWidth: Integer;
The GridLineWidth property determines the width of the lines between the cells in the
grid. The default value is 1 pixel. Larger values create heavier lines.
Example
This example includes a draw grid on a form. When the application runs and the form is
created, the width of the lines on the draw grid changes if the default column width of
the grid is over 90 pixels wide:
procedure TForm1.FormCreate(Sender: TObject);
begin
with DrawGrid1 do
begin
if DefaultColWidth > 90 then
GridLineWidth := 2
else
GridLineWidth := 1;
end;
end;
See also
ColWidths property, DefaultColWidth property, GridHeight property, GridWidth property,
RowHeights property
GridWidth property
Applies to
TDrawGrid, TStringGrid components
Declaration
property GridWidth: Integer;
Run-time and read only. The GridWidth property is the width of the grid in pixels. If the
grid is too wide to be fully displayed causing the user to scroll it to see its entire
contents, the value of GridWidth is the same as the ClientWidth property value for the
grid.
Example
This example uses a string grid and a label on a form. The label reports the width of the
grid.
procedure TForm1.FormCreate(Sender: TObject);
var
ARow, ACol: Integer;
begin
with StringGrid1 do
begin
for ARow := 1 to RowCount - 1 do
for ACol := 1 to ColCount - 1 do
Cells[ARow, ACol] := 'Pascal';
end;
Label1.Caption := IntToStr(StringGrid1.GridWidth) + ' pixels';
end;
See also
GridHeight property
GroupIndex property
Applies to
TMenuItem, TSpeedButton components
down state, until the user clicks another speed button belonging to the same group.
+
Speed buttons used in this way can present mutually exclusive choices to the user. +
Example
This code assures that the three speed buttons work together as a group:
+
SpeedButton1.GroupIndex := 1; +
+
SpeedButton2.GroupIndex := 1;
SpeedButton3.GroupIndex := 1;
See also
AllowAllUp property, Down property
+
G
For menu items
Declaration
property GroupIndex: Byte;
If your application has multiple forms, you’ll probably want your application’s main
menu to change as different forms become active. The alternative is for each form to
display its own menu within itself. MDI applications always merge the menus of child
windows with the main menu of the parent window. By using the GroupIndex property
for menu items, you can determine how menus are merged. You can choose to replace
or insert menu items in a menu bar.
Each menu item has a GroupIndex property value. By default, all menu items in a menu
bar have the same GroupIndex value, unless you explicitly change them. Each successive
menu item in a menu bar must have a GroupIndex value equal to or greater than the
previous menu item.
the item’s GroupIndex value is greater than all other GroupIndex values in the main
form’s menu bar, the item appears at the end of the menu. If the GroupIndex value is
between other GroupIndex values in the menu bar on the main form, the menu item
appears between other menu items, depending on the value.
For example, an item with a GroupIndex value of 2 would be inserted between items
with GroupIndex values of 1 and 3. An item with a GroupIndex value of 4 would appear
after all the other items.
Note The GroupIndex value must be different from all others in the menu bar on the main
form, or else the new menu item will replace one or more menu items with the same
GroupIndex value, which you may or may not want to do.
Any menu items in your container application with values of 1, 3, or 5 for their
GroupIndex properties are replaced by menu items with corresponding index values
from the OLE server application. The menu items from your OLE container with a
GroupIndex value other than 1, 3, or 5 won’t be replaced by menus from the server.
See also
AutoMerge property, FormStyle property
The Halt procedure stops the program and returns to the operating system. Exitcode is
+
an optional expression that specifies the exit code of your program. +
Example +
begin
if 1 = 1 then
begin
+
if 2 = 2 then
begin
+
if 3 = 3 then
begin +
end;
Halt(1); { Halt right here! }
end; +
end;
Canvas.TextOut(10, 10, 'This will not be executed');
H
end;
See also
Exit procedure, RunError procedure
Handle property
Applies to
All windowed controls; TApplication, TBitmap, TBrush, TCanvas, TFont, TIcon, TMetafile,
TPen, TPrinter objects; TDatabase, TFindDialog, TMainMenu, TMenuItem, TPopupMenu,
TQuery, TSession, TStoredProc, TTable components
Declaration
property Handle: HBitmap; {for TBitmap objects}
property Handle: HBrush; {for TBrush objects}
property Handle: HDC; {for TCanvas objects}
property Handle: HFont; {for TFont objects}
property Handle: HIcon; {for TIcon objects}
property Handle: HMetafile; {for TMetafile objects}
property Handle: HPen; {for TPen objects}
The Handle property lets you access the Windows GDI object handle, so you can access
the GDI object. If you need to use a Windows API function that requires the handle of a
pen object, you could pass the handle from the Handle property of a TPen object.
Example
The following code uses the Windows API function ShowWindow to display Form2 as an
icon, but does not activate it.
ShowWindow(Form2.Handle, SW_SHOWWINMINNOACTIVE);
See also
HandleAllocated method, HandleNeeded method
Example
The following code uses the Windows API function HiliteMenuItem to highlight the first
menu item in MainMenu1 on Form1.
HiliteMenuItem(Form1.Handle, MainMenu1.Handle, 0, MF_BYPOSITION+MF_HILITE);
For sessions
Declaration
property Handle: HDBISES;
Run-time and read only. The Handle property allows you to make direct calls to the
+
Borland Database Engine using this handle to the session (TSession). Under most
circumstances you should not need to use this property, unless your application
+
requires some functionality not encapsulated in the VCL. +
For tables, queries, and stored procedures +
Declaration +
property Handle: HDBICur;
Run-time and read only. The Handle property enables an application to make direct calls
+
to the Borland Database Engine API using this handle of a dataset component. +
Under most circumstances you should not need to use this property, unless your
application requires some functionality not encapsulated in the VCL. H
For databases
Declaration
property Handle: HDBIDB;
Run-time and read only. Use the Handle property to make direct calls to the Borland
Database Engine (BDE) API that require a database handle. Under most circumstances
you should not need to use this property, unless your application requires some
functionality not encapsulated in the VCL.
HandleAllocated method
Applies to
All controls
Declaration
function HandleAllocated: Boolean;
The HandleAllocated method returns True if a window handle for the control exists. If no
window handle exists, HandleAllocated returns False. If you query the Handle property of
a control directly, a handle is automatically created if it didn’t previously exist.
Therefore, you should call the HandleAllocated method if you don’t want a handle
created automatically for the control, but simply want to know if one exists.
Example
The following code displays the value of the handle of GroupBox1 if it exists. If not, it
displays a message.
var
TheValue: string;
begin
if GroupBox1.HandleAllocated then
TheValue := IntToStr(GroupBox1.Handle)
else TheValue := ’Handle not allocated.’;
Label1.Caption := TheValue;
end;
See also
HandleNeeded method
HandleException method
Applies to
TApplication component
Declaration
procedure HandleException(Sender: TObject);
The HandleException method handles the exceptions for the application. If an exception
passes through all the try blocks in your application code, your application
automatically calls the HandleException method, which displays a dialog box indicating
an error occurred. To assign other exception handling code for the application, use the
OnException event handler.
Example
The following code uses the default error handling:
try
{ Some code that may produce an exception goes here }
except
Application.HandleException(Self);
end;
See also
Application variable, OnException event
HandleNeeded method
Applies to
All controls
Declaration
procedure HandleNeeded;
The HandleNeeded method creates a window handle for the control if one doesn’t
+
already exist. +
Example
The following code creates a window handle for Button1:
+
Button1.HandleNeeded; +
See also +
Handle property, HandleAllocated method
+
HasFormat method +
Applies to
TClipboard object
H
Declaration
procedure HasFormat(Format: Word): Boolean;
The HasFormat method determines if the Clipboard object contains a particular format.
If HasFormat is True, the format is present; if False, the format is absent. The Clipboard
object keeps a list of available formats in the Formats array property.
These are the possible values of the Format parameter:
Value Meaning
CF_TEXT Text with each line ending with a CR-LF combination. A null character identifies
the end of the text.
CF_BITMAP A Windows bitmap graphic.
CF_METAFILE A Windows metafile graphic.
CF_PICTURE An object of type TPicture.
CF_OBJECT Any persistent object.
Example
This example uses a button on a form. When the user clicks the button, a message box
appears if there is no text on the Clipboard; otherwise, you don’t see anything happen.
procedure TForm1.Button1Click(Sender: TObject);
begin
if not Clipboard.HasFormat(CF_TEXT) then
MessageDlg('There is no text on the Clipboard', mtInformation,
[mbOK],0);
end;
See also
Assign method, FormatCount property, Formats property, GetComponent method,
SetComponent method
HasItems property
Applies to
TOutlineNode object
Declaration
property HasItems: Boolean;
Run-time and read only. The HasItems property determines if an outline item has any
subitems. Subitems appear below and indented from their parent item when the parent
is expanded. The Index value of the parent item is one less than the Index value of its first
subitem. HasItems is True if the item has subitems, or False if the item has no subitems.
Example
The following code expands the selected item of Outline1 if it has subitems:
with Outline1[Outline1.SelectedItem] do
if HasItems then Expand;
See also
GetFirstChild method, GetLastChild method, GetNextChild method, GetPrevChild method
See also
GlobalAlloc function, GlobalLock function
Height property
Applies to
All controls; TBitmap, TFont, TGraphic, TIcon, TMetafile, TPicture objects; TForm, TScreen
components
Declaration
property Height: Integer;
Example
The following code doubles the height of a list box control:
ListBox1.Height := ListBox1.Height * 2;
See also
ClientHeight property, SetBounds method, Width property
Example
To following code sets a form’s height to half the height of the screen:
Form1.Height := Screen.Height div 2;
See also
Screen variable, Width property
For fonts
The Height property is the height of the font in pixels. It is the size of the font plus the
font’s internal leading. If you are concerned with the size of the font on the screen—the
number of pixels the font needs—use the Height property. If you want to specify a font‘s
size using points, use the Size property instead.
Delphi calculates Height using this formula:
Font.Height = -Font.Size * Font.PixelsPerInch / 72
Therefore, whenever you enter a point size in the Height property, you’ll notice the Size
property changes to a negative value. Conversely, if you enter a positive Size value, the
Height property value changes to a negative value.
Example
This example uses button and a label on a form. When the user clicks the button, the
height of the font changes to 36 pixels on the screen:
procedure TForm1.Button1Click(Sender: TObject);
begin
Label1.Font.Height := 36;
end;
Example
This example uses a bitmap button on a form. When the user clicks the button, the Help
contents screen of the specified Help file appears.
procedure TForm1.BitBtn1Click(Sender: TObject);
begin
Application.HelpFile := 'MYHELP.HLP';
Application.HelpCommand(HELP_CONTENTS, 0);
end;
See also
Application variable, HelpContext method, HelpContext property, HelpFile property,
HelpJump method
HelpContext method
Applies to
TApplication component
Declaration
function HelpContext(Context: THelpContext): Boolean;
The HelpContext method calls WinHelp, the Windows Help system program, if the
HelpFile property is assigned a file to use for Help. HelpContext passes the file name
contained in HelpFile and the context number passed in Context parameter. For example,
if you specify the Context value as 714, the HelpContext method displays the screen with
the context help ID of 714 in the Help file.
HelpContext returns False if HelpFile is an empty string, meaning the application has no
Help file assigned. In all other cases, HelpContext returns True.
Example
This example uses a bitmap button on a form. When the user clicks the button, the
screen with the context number of 714 in the DATA.HLP Help file appears:
procedure TForm1.BitBtn1Click(Sender: TObject);
begin
Application.HelpFile := 'DATA.HLP';
Application.HelpContext(714);
end;
See also
Application variable, HelpFile property, OnHelp event
HelpContext property
Applies to
All controls; Exception, TColorDialog, TFindDialog, TFontDialog, TMenuItem, TPopupMenu,
TOpenDialog, TPrintDialog, TPrinterSetupDialog, TReplaceDialog, TSaveDialog
components
Declaration
property HelpContext: THelpContext;
The HelpContext property provides a context number for use in calling context-sensitive
online Help. Each screen in the Help system should have a unique context number.
When a component is selected in the application, pressing F1 displays a Help screen.
Which Help screen appears depends on the value of the HelpContext property.
Example
The following code associates a Help file with the application, and makes the screen
with a context number of 7 the context-sensitive Help screen for the Edit1 edit box:
procedure TForm1.FormActivate(Sender: TObject);
begin
Application.HelpFile := ’MYHELP.HLP’;
Edit1.HelpContext := 7;
end;
See also
HelpContext method, HelpFile property, HelpJump method, OnHelp event
HelpFile property
Applies to
TApplication component
Declaration
function HelpJump(const JumpID: string): Boolean;
The HelpJump method calls WinHelp, the Windows Help system program, if the HelpFile
property is assigned a file to use for Help. HelpJump passes the file name contained in
HelpFile and the context string specified in the JumpID parameter. For example, if you
specify the JumpID value as ‘vclDefaultProperty', the HelpJump method displays the
screen in the Help file that has the context string ‘vclDefaultProperty'.
HelpJump returns False if HelpFile is an empty string, meaning the application has no
Help file assigned. In all other cases, HelpJump returns True.
Example
This example uses a bitmap button on a form. When the user clicks the button, the Help
screen describing the Default property in the DELPHI.HLP file appears, because the
Default property screen has the a JumpID string of ‘vclDefaultProperty'.
procedure TForm1.BitBtn1Click(Sender: TObject);
begin
Application.HelpFile := 'DELPHI.HLP';
Application.HelpJump('vclDefaultProperty');
end;
See also
Application variable, HelpCommand method, HelpContext method, HelpContext property,
HelpFile property, OnHelp event
Hi function System
Declaration
function Hi(X): Byte;
The Hi function returns the high-order byte of X as an unsigned value. X is an
expression of type Integer or Word.
Example
var B: Byte;
begin
B := Hi($1234); { $12 }
end;
See also
Lo function, Swap function
Hide method
Applies to
TForm component, All controls
Declaration
procedure Hide;
The Hide method makes a form or control invisible by setting the Visible property of the
form or control to False. Although a form or control that is hidden is not visible, you can
still set the properties of the form or control, or call its methods.
Example
This code uses a button and a timer on a form. When the user clicks the button, the form
disappears for the period of time specified in the Interval property of the timer control,
then the form reappears:
procedure TForm1.Button1Click(Sender: TObject);
begin
Timer1.Enabled := True;
Hide;
end;
procedure TForm1.Timer1Timer(Sender: TObject);
begin
Visible := True;
Timer1.Enabled := False;
end;
Example
This example uses an edit box and a memo on a form. When the user jumps from one
control to the other, selected text remains selected in the memo, but not in the edit box.
procedure TForm1.FormCreate(Sender: TObject);
begin
Edit1.HideSelection := True;
Memo1.HideSelection := False;
end;
See also
AutoSelect property
Example
function Sum( var X: array of Double): Double;
var
I: Word;
S: Double;
begin
S := 0; { Note that open array index range is always zero-based. }
for I := 0 to High(X) do S := S + X[I];
Sum := S;
end;
procedure TForm1.Button1Click(Sender: TObject);
var
List1: array[0..3] of Double;
List2: array[5..17] of Double;
X: Word;
S, TempStr: string;
begin
for X := Low(List1) to High(List1) do
List1[X] := X * 3.4;
for X := Low(List2) to High(List2) do
List2[X] := X * 0.0123;
Str(Sum(List1):4:2, S);
S := 'Sum of List1: ' + S + #13#10;
S := S + 'Sum of List2: ';
Str(Sum(List2):4:2, TempStr);
S := S + TempStr;
MessageDlg(S, mtInformation, [mbOk], 0);
end;
See also
Low function
Example
This example uses an edit box and a list box on a form. Items are added to the list box
and a Help Hint is assigned to both controls. The last statement enables the Help Hints
for the entire application.
procedure TForm1.FormCreate(Sender: TObject);
var
I: Integer;
begin
Edit1.Hint := 'Enter your name';
Edit1.ShowHint := True;
with ListBox1 do
begin
for I := 1 to 10 do
Items.Add('Item ' + IntToStr(I));
Hint := 'Select an item';
ShowHint := True;
end;
Application.ShowHint := True;
end;
To see a example that displays the hints of controls in some place other than in a Help
Hint box, see the OnHint example.
See also
GetLongHint function, GetShortHint function, HintColor property, HintPause property,
ShowHint property for controls, ShowHint property for the application
HintColor property
Applies to
TApplication component
Declaration
property HintColor: TColor
Description
Run time only. The HintColor property determines the color of the hint boxes for the
Help Hints of the controls in the application. For a table of possible color values, see the
Color property.
Example
This example includes an control that has a Hint property value and has its ShowHint
property value set to True. When the application runs and the user places the mouse
cursor over the control, a Help Hint appears for the control in an aqua hint box after a
delay of 1000 milliseconds:
procedure TForm1.FormCreate(Sender: TObject);
begin
Application.ShowHint := True;
Application.HintColor := clAqua;
Application.HintPause := 1000;
end;
See also
Application variable, Hint property, HintPause property, ShowHint property, TColor type
See also
Application variable, Hint property, HintColor property, ShowHint property
Hints property
Applies to
TDBNavigator component
Declaration
property Hints: TStrings;
The Hints property allows you to customize the Help Hints for the buttons on the
database navigator. Each hint is a string. The first string in the string object becomes the
Help Hint for the first button on the navigator. The seventh hint becomes the Help Hint
for the seventh button (the Edit button).
If you don’t want to change the Help Hint for every button, enter an empty string (‘’) for
the Help Hint you want to stay the same, or simply leave the line blank if you are using
the string list property editor of the Object Inspector for the Hints property.
Example
This example uses a database navigator and a button on a form. When the user clicks the
button, the Help Hints for the navigator are modified.
procedure TForm1.Button1Click(Sender: TObject);
var
NewStrings: TStringList;
begin
NewStrings := TStringList.Create;
with NewStrings do
begin
Add('Beginning of dataset');
Add('Previous record');
Add('');
Add('End of dataset');
end;
DBNavigator1.Hints := NewStrings;
DBNavigator1.ShowHint := True;
end;
See also
Hint property, HintColor property, HintPause property
HistoryList property
Applies to
TOpenDialog, TSaveDialog components
Declaration
property HistoryList: TStrings ;
The HistoryList property contains strings that appear in the File Name drop-down
combo box of an Open or Save dialog box when the user opens it. Because only a File
Name combo box can have a value for the HistoryList property, the FileEditStyle
property value of the dialog box must be fsComboBox. If the FileEditStyle property value
is fsEdit, the strings in the HistoryList property aren’t used by the dialog box.
Your application can use the HistoryList property to create a list of previous files names
opened or saved with the dialog box. Use a TStringList object to keep a list of file names,
and assign this object to the HistoryList property.
Note When an Open or Save dialog box is open, your application won’t be able to access the
HistoryList property. Therefore, your application must work with HistoryList before the
dialog box opens or after it closes.
Example
This example uses an Open dialog box and a button. The code creates a string list object
and stores each file the user selects in the Open dialog box in it. Each time the clicks the
button to open the dialog box, the string list is assigned to the HistoryList property.
HorzScrollBar property
Applies to
TForm, TScrollBox components
Declaration
property HorzScrollBar: TControlScrollBar;
The HorzScrollBar property is the form’s or scroll box’s horizontal scroll bar. The values
of HorzScrollBar’s nested properties determines how the horizontal scroll bar behaves.
To make a horizontal scroll bar appear on a form or scroll box, the nested properties of
HorzScrollBar must be set like this:
• Visible must be True.
• The value of the Range property must be greater than the value of the ClientWidth
property of the form or the Width property of the scroll box.
Example
This example implements a horizontal scroll bar on the form. The scroll bar scrolls the
form 100 pixels more than the form width:
procedure TForm1.FormCreate(Sender: TObject);
begin
ClientWidth := 300;
with HorzScrollBar do
begin
Increment := 4;
Position := 0;
Range := ClientWidth + 100; {Range must be greater than the form’s client width}
Visible := True;
end;
end;
See also
AutoScroll property, Increment property, Position property, Range property, ScrollPos
property, VertScrollBar property, Visible property
Icon property
Applies to
TPicture object; TApplication, TForm components
For forms
Declaration
property Icon: TIcon
The Icon property determines the icon that is displayed when the window or form is
minimized. If you don’t assign a specific icon to Icon, the form uses the application’s
icon.
Example
This code assigns an icon to a form when the form is created:
procedure TForm1.FormCreate(Sender: TObject);
begin
Icon.LoadFromFile('MYICON.ICO');
end;
See also
Graphic property
For an application
Declaration
property Icon: TIcon;
The value of the Icon property determines which icon represents the application when it
is minimized or displayed in the Program Manager.
Example
This line of code uses the icon in the MYAPP.ICO files for the application’s icon:
Application.Icon.LoadFromFile('MYAPP.ICO');
See also
Application variable, LoadFromFile method, Minimize method, SaveToFile method
Example
var
IntVar: Integer;
LongintVar: Longint;
begin
Inc(IntVar); { IntVar := IntVar + 1 }
Inc(LongintVar, 5); { LongintVar := LongintVar + 5 }
end;
See also
Dec procedure, Pred function, Succ function
Inch property
Applies to
TMetafile object
See also
Exclude procedure
Increment property
Applies to
TControlScrollBar component
Declaration
property Increment: Integer;
The Increment property determines how many positions the scroll box in a form scroll
bar moves when the user clicks one of the small end arrows. The default value is 8.
Example
This example implements a horizontal scroll bar on the form. The scroll bar scrolls the
form 100 pixels more than the form width. Each time the user clicks a scroll arrow on the
scroll bar, the form scrolls 7 pixels:
procedure TForm1.FormCreate(Sender: TObject);
begin
ClientWidth := 300;
with HorzScrollBar do
begin
Position := 0;
Increment := 7;
Range := ClientWidth + 100; {Range must be greater than the form’s client width}
Visible := True;
end;
end;
See also
HorzScrollBar property, Position property, Range property, ScrollPos property,
VertScrollBar property
Index property
Applies to
TOutlineNode object; TBCDField, TBlobField, TBooleanField, TBytesField, TCurrencyField,
TDateField, TDateTimeField, TFloatField, TGraphicField, TIntegerField, TMemoField,
TSmallintField, TStringField, TTimeField, TVarBytesField, TWordField components
Example
The following code tests to determine if the selected item is the top item in the outline.
with Outline1 do
if Items[SelectedItem].Index = 1 then
{ The selected item is the top item }
else
{ The selected item is not the top item };
See also
Add method, Delete method, EndUpdate method, Insert method
Example
{ Get the current available indicies }
Table1.IndexDefs.Update;
{ Find one which combines Customer Number (‘CustNo’) and Order Number (‘OrderNo’) }
for I := 0 to Table1.IndexDefs.Count - 1 do
if Table1.IndexDefs.Items[I].Fields = ‘CustNo;OrderNo’ then
IndexFieldCount property
Applies to
TTable component
Declaration
property IndexFieldCount: Integer;
Run-time only. The IndexFieldCount property is the number of actual fields for the
current index. If you are using the primary index for the component, this value will be
one. If the component is not Active, the value of IndexFieldCount will be zero.
Example
TotalLen := 0;
with Table1 do
{ Calculate the total length of the index }
for I := 0 to IndexFieldCount - 1 do
Inc(TotalLen, IndexFields[I].FieldDef.DataSize);
IndexFieldNames property
Applies to
TTable component
Declaration
property IndexFieldNames: string;
The IndexFieldNames property is used with an SQL server to identify the columns to be
used as an index for the TTable. Separate the column names with semicolon characters
(“;”). If you have too many column names or the names are too long to fit within the 255
character limit, use column numbers instead of names.
Note IndexFieldNames and IndexName are mutually exclusive. Setting one will clear the other.
Example
Query1.IndexFieldNames := ‘CustNo;OrderNo’;
IndexFields property
Applies to
TTable component
Declaration
property IndexFields[Index: Integer]: TField;
Run-time only. The IndexFields property gives you access to information about each field
of the current index for the dataset. The Active property must be True or the information
will not be valid.
Example
S := '';
with Table1 do
{ Create a composite string with the index’s names separated by “@” }
for I := 0 to IndexFieldCount - 1 do
S := S + '@' + IndexFields[I].FieldName;
Example
Table1.IndexName := ‘CustNoIndex’;
See also
MasterFields property, MasterSource property
IndexOf method
Applies to
TList, TStringList, TStrings objects; TFieldDefs, TIndexDefs, TMenuItem components
Example
This example uses a main menu named File1, a button, and a label on a form. The File1
menu contains three menu commands, Open, Save, and Close. Delphi automatically
names these menu items Open1, Save1, and Close1. This code returns the position of the
Close command in the File menu and reports it as the caption of the label.
See also
FindItem method
Example
The following code adds an object to MyList if it isn’t already in the list.
if MyList.IndexOf(MyObject)=-1 then MyList.Add(MyObject);
See also
Add method, Count property
Example
This example uses a combo box that contains five strings (enter them as the value of the
Items property with the Object Inspector) and a label. When the user selects a string in
the combo box, the index of the selected string appears as the caption of the label.
procedure TForm1.ComboBox1Click(Sender: TObject);
begin
Label1.Caption := IntToStr(ComboBox1.Items.IndexOf(ComboBox1.SelText));
end;
This example uses a file list box, a directory list box, and a label on a form. When the
user uses the directory list box to change directories, a message appears and the color of
the form changes if the file AUTOEXEC.BAT is in the new directory. The code is written
+
in the OnChange event of the directory list box: +
procedure TForm1.DirectoryListBox1Change(Sender: TObject);
begin
FileListBox1.Directory := DirectoryListBox1.Directory;
+
if FileListBox1.Items.IndexOf('AUTOEXEC.BAT') > -1 then
begin
+
Color := clYellow;
Label1.Caption := 'You are in the root directory!'; +
end;
end; +
See also
IndexOfObject method, Strings property
+
+
For TIndexDefs objects
I
Declaration
function IndexOf(const Name: string): Integer;
The IndexOf method returns the index of the entry in Items whose Name property
matches the Name parameter.
IndexOfObject method
Applies to
TStringList, TStrings objects
Declaration
function IndexOfObject(AObject: TObject): Integer;
The IndexOfObject method returns the position of an object stored in the Objects property
of a string object. Specify the object you want to locate as the value of the AObject
parameter. The first position in the list of objects is 0. If the object is not in the list of
objects, IndexOfObject returns -1.
Example
The following code determines if MyObject is the first object in MyStringList.
if MyStringList.IndexOfObject(MyObject)=0 then
{ MyObject is the first object in the list };
See also
AddObject method, IndexOf method, InsertObject method
InitialDir property
Applies to
TOpenDialog, TSaveDialog components
Declaration
property InitialDir: string;
The InitialDir property determines the current directory when the dialog box first
appears and value of the InitialDir property is shown as the current directory in the
directory tree. Only files in the current directory appear in the dialog box’s list box of file
names. After the dialog box appears, users can then use the directory tree to change to
another directory if they want.
When specifying the initial directory, include the full path name. For example,
C:\WINDOWS\SYSTEM
If no initial directory is specified, the directory that is current when the dialog box
appears remains the current directory. The same is true if you specify a directory that
does not exist.
Example
This code specifies C:\WINDOWS as the initial directory when the dialog box appears,
displays the dialog box, and displays the name of the file the user selects with the dialog
box in a label on the form:
procedure TForm1.Button1Click(Sender: TObject);
begin
OpenDialog1.InitialDir := 'C:\WINDOWS';
if OpenDialog1.Execute then
Label1.Caption := OpenDialog1.FileName;
end;
See also
Filter property
See also
ScreenSize typed constant, WindowOrg typed constant, WindowSize typed constant,
WindowTitle variable
InPlaceActive property
Applies to
TOLEContainer component
Declaration
property InPlaceActive: Boolean;
Run-time and read only. The InPlaceActive property specifies whether the OLE object in
an OLE container is active in-place. If so, the value of InPlaceActive is True. If the object is
deactivated, or activated in its own window (not in place), the value of InPlaceActive is
False.
When an OLE object is active in-place, the OLE server application controls the editing of
the OLE object from within the OLE container application. The OLE server might
replace menu items and the status bar of the OLE container.
Example
The following code waits until an OLE object is activated in place before unlocking
Panel1. Attach this code to the OnActivate event handler of OLEContainer1.
procedure TForm1.OleContainer1Activate(Sender: TObject, Activating:Boolean);
begin
if OLEContainer1.InPlaceActive then
Panel1.Locked := False;
end;
See also
Active property, GroupIndex property
Example
This example displays an input dialog box when the user clicks the button on the form.
The input dialog box includes a prompt string and a default string. The string the user
enters in the dialog box is stored in the InputString variable.
uses Dialogs;
procedure TForm1.Button1Click(Sender: TObject);
var
InputString: string;
begin
InputString:= InputBox('Input Box', 'Prompt', 'Default string');
end;
See also
MessageDlg function, MessageDlgPos function
Example
This example uses a button and a label on the form. When the user clicks the button, a
the input box displays. If the user chooses OK, the string that appears in the edit box of
the dialog box displays as the caption of the label on the form. If the user chooses
Cancel, the dialog box closes and the caption of the label remains unchanged.
procedure TForm1.Button1Click(Sender: TObject);
var
NewString: string;
ClickedOK: Boolean;
begin
NewString := 'Default String';
Label1.Caption := NewString;
ClickedOK := InputQuery('Input Box', 'Prompt', NewString);
if ClickedOK then { NewString contains new input string }
Label1.Caption := 'The new string is ''' + NewString + '''';
end;
See also
MessageDlg function, MessageDlgPos function
Insert method
Applies to
TList, TMenuItem, TStringList, TStrings objects; TOutline, TTable, TQuery components
Declaration
procedure Insert(Index: Integer; const S: string);
The Insert method inserts a string into the list of strings in a string or string list object.
The string S is inserted into the position in the list indicated by the value of Index. The
index is zero-based, so the first position in the list has an index value of 0.
Example
This example uses a list box and a button on a form. When the form appears, it contains
five items. When the user clicks the button, another string is inserted at the top of the list
of items:
procedure TForm1.FormCreate(Sender: TObject);
var
I: Integer;
begin
for I := 1 to 5 do
ListBox1.Items.Add('Item ' + IntToStr(I));
end;
procedure TForm1.Button1Click(Sender: TObject);
begin
See also
Add method, AddStrings method, Clear method, Delete method, IndexOf method,
InsertObject method
Example
This example inserts a new menu item after the first item in a menu named FileMenu:
procedure TForm1.Button1Click(Sender: TObject);
var
NewItem: TMenuItem;
begin
NewItem := TMenuItem.Create(FileMenu);
NewItem.Caption := 'Do this';
FileMenu.Insert(1, NewItem);
end;
See also
Add method, Count property, Delete method
For outlines
Applies to
TOutline component
Declaration
function Insert(Index: Longint; const Text: string): Longint;
Description
The Insert method inserts an outline item (TOutlineNode object) into an outline. The
value of the Index and Text parameters are stored in the Index and Text properties of the
inserted item. Insert returns the Index property value of the inserted item.
The inserted item appears in the outline position determined by the Index parameter. It
is inserted at the same level as the item that previously resided at this position.
Therefore, the inserted item and the original item are siblings and share the same parent.
The original item and all other outline items that appear after the inserted item are
+
moved down one row and are reindexed with valid Index values. This happens
automatically unless the BeginUpdate method was called.
+
Note To insert an item as the last top-level item in an outline, pass zero (0) in the Index
parameter.
+
Example
+
The following code inserts an item as a sibling of the selected item. +
begin
Outline1.Insert(Outline1.SelectedItem, 'New item');
end;
+
See also
+
Add method, AddChild method, AddChildObject method, InsertObject method, MoveTo
method
+
I
For tables and queries
Declaration
procedure Insert;
The Insert method puts the dataset into Insert state and opens a new, empty record at the
current cursor location. When an application calls Post, the new record will be inserted
in the dataset in a position based on its index, if defined. To discard the new record, use
Cancel.
This method is valid only for datasets that return a live result set.
Note For indexed tables, the Append and Insert methods will both put the new record in the
correct location in the table, based on the table’s index. If no index is defined on the
underlying table, then the record will maintain its position—Append will add the record
to the end of the table, and Insert will insert it at the current cursor position. In either
case, posting a new record may cause rows displayed in a data grid to change as the
dataset follows the new row to its indexed position and then fetches data to fill the data
grid around it.
Example
with Table1 do
begin
{ Move to the end ot the component }
Last;
Insert;
FieldByName(‘CustNo’).AsString := ‘9999’;
{ Fill in other fields here }
if { you are sure you want to do this} then Post
else { if you changed your mind } Cancel;
end.
Example
var
S: string;
begin
S := 'Honest Lincoln';
Insert('Abe ', S, 8); { 'Honest Abe Lincoln' }
end;
See also
Concat function, Copy function, Delete procedure, Length function, Pos function
InsertComponent method
Applies to
All components
Declaration
procedure InsertComponent(AComponent: TComponent);
The InsertComponent method makes the component own the component passed in the
AComponent parameter. The component is added to the end of the Components array
property. The inserted component must have no name (no specified Name property
value), or the name must be unique among all others in the Components list.
When the owning component is destroyed, AComponent is destroyed also.
Example
The following code inserts NewButton into the Components array of Form1.
Form1.InsertComponent(NewButton);
See also
RemoveComponent method
See also
Parent property, RemoveControl method
InsertObject method
Applies to
TStringList, TStrings objects, TOutline component
The InsertObject method inserts a string into the list of strings and an object into the list
of objects in a string or string list object. Specify the string you want to insert as the value
of the S parameter, and the object you want to insert as the value of the AObject
parameter. The Index parameter identifies the position of the string and object in their
respective string and object lists. Because the index is zero-based, the first position in
each list has an Index value of 0.
If your application calls InsertObject when the list of items is sorted, an EListError
exception is raised.
Example
The following code inserts the components of Form1 into the first position of the Lines
list of Memo1.
var
I: Integer;
begin
for I := 0 to Form1.ComponentCount-1 do
begin
with Form1.Components[i] as TComponent do
Memo1.lines.InsertObject(0, Name, Self);
end;
end;
See also
AddObject method, IndexOfObject method, Insert method, Objects property, Strings
property
For outlines
Applies to
TOutline component
Declaration
function InsertObject(Index: Longint; const Text: string; const Data: Pointer): Longint;
Description
The InsertObject method inserts an outline item (TOutlineNode object) containing data
into an outline. The value of the Index and Text parameters are stored in the Index and
Text properties of the inserted item. The Data parameter specifies the Data property
value of the new item. Insert returns the Index property value of the inserted item.
The inserted item appears in the outline position determined by the Index parameter. It
will be inserted at the same level as the item that previously resided at this position.
Therefore, the inserted item and the original item will be siblings and share the same
parent. The original item and all other outline items that appear after the inserted item
are moved down one row and are reindexed with valid Index values. This is done
automatically unless the BeginUpdate method was called.
To insert an item as the last top-level item in an outline, pass zero (0) in the Index
+
parameter. +
Example
The following code creates a bitmap object named Bitmap1 and inserts an outline item
+
containing Bitmap1 into the first level of Outline1. +
+
var
Bitmap1: TBitmap;
begin
Bitmap1 := TBitmap.Create;
Outline1.InsertObject(1, 'New item', Bitmap1); +
end;
+
See Also
Add method, AddChild method, AddChildObject method, Insert method, MoveTo method +
InsertOLEObjectDlg function
I
Toctrl
Declaration
function InsertOleObjectDlg(Form: TForm; HelpContext: THelpContext;
var PInitInfo: Pointer): Boolean;
InsertOLEObjectDlg displays the Insert Object dialog box. Use this function to allow the
user to specify the OLE object initialization information by using the Insert Object dialog
box.
InsertOLEObjectDlg returns True if the user specifies an OLE object and chooses OK from
the Insert Object dialog box. InsertOLEObjectDlg returns False if the user doesn’t specify
an OLE object or chooses Cancel in the dialog box.
These are the parameters of InsertOLEObjectDlg:
Field Description
Form The form that owns the Insert Object dialog box.
HelpContext A Help context identification number that is used if the user chooses Help from within
the Insert Object dialog box. If you pass 0 for HelpContext, no Help button appears in
the Insert Object dialog box. Pass a number other than 0 if you want to provide
context-sensitive online Help.
PInitInfo If InsertOLEObject returns True, InsertOLEObjectDlg modifies the PInitInfo pointer
parameter to point to OLE initialization information. Initialize the OLE object by
assigning this pointer to the PInitInfo property. When your application is finished with
the PInitInfo pointer, it should be released with ReleaseOLEInitInfo.
Example
The following code displays the Insert Object dialog box. If the user specifies an object
and chooses OK, OLEContainer1 is initialized. After initialization, the OLE information is
released.
var
Info: Pointer;
begin
if InsertOLEObjectDlg(Form1, 0, Info) then
begin
OLEContainer1.PInitInfo := Info;
ReleaseOLEInitInfo(Info);
end;
end;
See also
LinksDlg function, PasteSpecialDlg function
InsertRecord method
Applies to
TTable, TQuery components
Declaration
procedure InsertRecord(const Values: array of const);
The InsertRecord method inserts a new record into the dataset using the field values
passed in the Values parameter. The assignment of the elements of Values to fields in the
record is sequential; the first element is assigned to the first field, the second to the
second, etc. The number of field values passed in Values may be fewer than the number
of actual fields in the record; any remaining fields are left unassigned and are NULL.
The type of each element of Values must be compatible with the type of the field in that
the field must be able to perform the assignment using AsString, AsInteger, etc.,
according the type of the Values element.
This method is valid only for datasets that return a live result set.
Note For indexed tables, the AppendRecord and InsertRecord methods will both put the new
record in the correct location in the table, based on the table’s index. If no index is
defined on the underlying table, then the record will maintain its position—
AppendRecord will add the record to the end of the table, and InsertRecord will insert it at
the current cursor position. In either case, posting a new record in a data grid may cause
all the rows before and after the new record to change as the dataset follows the new
row to its indexed position and then fetches data to fill the grid around it.
Example
Table1.InsertRecord([9998, ‘Lesh’, ‘Phil’]);
See also
TField component
IntegralHeight property
Applies to
TDBListBox, TDirectoryListBox, TFileListBox, TListBox component
Declaration
property IntegralHeight: Boolean;
The IntegralHeight property controls the way the list box represents itself on the form. If
IntegralHeight is True, the list box shows only entries that fit completely in the vertical
space, and the bottom of the list box moves up to the bottom of the last completely
drawn item in the list. If IntegralHeight is False, the bottom of the list box is at the location
determined by its ItemHeight property, and the bottom item visible in the list might not
be complete.
If the list box has a Style property value of lbOwerDrawVariable, setting the IntegralHeight
property to True has no effect.
If the Style property value of the list box is lsOwnerDrawFixed, the height of the list box at
design time is always an increment of the ItemHeight value.
Example
This example uses a list box on a form. To try it, enter as many strings in the Items
property as you like using the Object Inspector. When the application runs, the list box
displays only entries that fit completely in the vertical space, and the bottom of the list
box moves up to the bottom of the last string in the list box if the form is less than 300
pixels in height:
procedure TForm1.FormCreate(Sender: TObject);
begin
if Height < 300 then
ListBox1.IntegralHeight := True
else
ListBox1.IntegralHeight := False;
end;
See also
ItemHeight property, Items property
Interval property
Applies to
TTimer component
Declaration
property Interval: Word;
The Interval property determines in milliseconds the amount of time that passes before
the timer component initiates another OnTimer event.
You can specify any value between 0 and 65,535 as the interval value, but the timer
component won’t call an OnTimer event if the value is 0. The default value is 1000 (one
second).
Example
The code in this OnTimer event handler moves a ball, the shape component (TShape)
slowly across a form.
procedure TForm1.Timer1Timer(Sender: TObject);
begin
Timer1.Interval := 100;
Shape1.Shape := stCircle;
Shape1.Left := Shape1.Left + 1;
end;
See also
+
IntToStr function
+
IntToStr function SysUtils +
Declaration
+
function IntToStr(Value: Longint): string; I
The IntToStr function converts an integer into a string containing the decimal
representation of that number.
Example
This example uses a button and an edit box on a form. The code assigns a value to the
Value variable and displays the string representation of the Value variable in the edit
box.
procedure TForm1.Button1Click(Sender: TObject);
var
Value: Integer;
begin
Value := 1234;
Edit1.Text := IntToStr(Value);
end;
See also
IntToHex function, StrToInt function
Invalidate method
Applies to
All controls; TForm component
Declaration
procedure Invalidate;
The Invalidate method forces a control to repaint as soon as possible.
Example
The following code invalidates Form1.
Form1.Invalidate;
See also
Refresh method, Update method
Example
var
F: file of Byte;
begin
if OpenDialog1.Execute then begin
AssignFile(F, OpenDialog1.FileName);
{$I–}
Reset(F);
{$I+}
if IOResult = 0 then
MessageDlg('File size in bytes: ' + IntToStr(FileSize(F)),
mtInformation, [mbOk], 0);
else
MessageDlg('File access error', mtWarning, [mbOk], 0);
end;
end;
IsIndexField property
Applies to
TBCDField, TBlobField, TBooleanField, TBytesField, TCurrencyField, TDateField,
TDateTimeField, TFloatField, TGraphicField, TIntegerField, TMemoField, TSmallintField,
TStringField, TTimeField, TVarBytesField, TWordField components
See also
EditMask property
IsNull property
Applies to
TParam object; TBCDField, TBlobField, TBooleanField, TBytesField, TCurrencyField,
TDateField, TDateTimeField, TFloatField, TGraphicField, TIntegerField, TMemoField,
TSmallintField, TStringField, TTimeField, TVarBytesField, TWordField components
Example
{ Set the CustNo parameter to 999 if it is null }
with Params.ParamByName(‘CustNo’) do
if IsNull then AsInteger := 999;
For fields
Declaration
property IsNull: Boolean;
Run-time and read only. IsNull returns True if the value of the field is NULL.
See also
Required property
IsSQLBased property
Applies to
TDataBase component
Declaration
property IsSQLBased: Boolean;
Run-time and read only. IsSQLBased is True if the TDatabase component uses any driver
other than ‘STANDARD’. If you are accessing a dBASE or Paradox database or ASCII
file, IsSQLBased will be False.
IsValidChar method
Applies to
TBCDField, TBlobField, TBooleanField, TBytesField, TCurrencyField, TDateField,
TDateTimeField, TFloatField, TGraphicField, TIntegerField, TMemoField, TSmallintField,
TStringField, TTimeField, TVarBytesField, TWordField components
Declaration
function IsValidChar(InputChar: Char): Boolean; virtual;
IsValidChar is used by data-aware controls to determine if a particular character entered
in the field is valid for the field. TIntegerField, TSmallintField and TWordField allow ‘+’, ‘-’
and ‘0’ to ‘9’. TBCDField and TFloatField also allow ‘E’, ‘e’, and the DecimalSeparator
+
character. All other fields accept all characters. +
See also
DecimalSeparator variable
+
+
IsValidIdent function SysUtils +
Declaration +
function IsValidIdent(const Ident: string): Boolean;
IsValidIdent returns True if the given string is a valid identifier. An identifier is defined as +
a character from the set ['A'..'Z', 'a'..'z', '_'] followed by zero or more characters from the
set ['A'..'Z', 'a'..'z', '0..'9', '_']. +
Note All component names must be valid Object Pascal identifiers.
I
IsVisible property
Applies to
TOutlineNode object
Declaration
property IsVisible: Boolean;
Run-time and read only. The IsVisible property indicates whether the outline item is
visible within the TOutline component. An item is visible if it is on level 1 or if all its
parents are expanded.
Example
The following code expands the branch of the selected outline item if it isn’t visible.
with Outline1.Items[Outline1.SelectedItem] do
if not IsVisible then FullExpand;
See also
Expanded property, Level property
ItemAtPos method
Applies to
TDBListBox, TDirectoryListBox, TFileListBox, TListBox, TTabSet components
Applies to
TDBListBox, TDirectoryListBox, TFileListBox, TListBox components
Declaration
function ItemAtPos(Pos: TPoint; Existing: Boolean): Integer;
The ItemAtPos method returns the index of the list box indicated by the coordinates of a
point on the control. The Pos parameter is the point in the control in window
coordinates.
If Pos is beyond the last item in the list box, the value of the Existing variable determines
the returned value. If you set Existing to True, ItemAtPos returns -1, indicating that no
item exists at that point. If you set Existing to False, ItemAtPos returns the position of the
last item in the list box.
ItemAtPos is useful for detecting if an item exists at a particular point in the control.
Example
This example uses a list box, and edit box, and a button on a form. When the user clicks
the button, the index value of the item in the list box which contains the point specified
in the code appears in the edit box:
procedure TForm1.Button1Click(Sender: TObject);
var
Value: Integer;
APoint: TPoint;
begin
APoint.X := 30;
APoint.Y := 50;
Value := ListBox1.ItemAtPos(APoint, False);
Edit1.Text := IntToStr(Value);
end;
See also
ItemIndex property, Items property
Declaration
function ItemAtPos(Pos: TPoint): Integer;
The ItemAtPos method returns the index of the tab indicated by the coordinates of a
point on the control. The Pos parameter is the point in the control in window
coordinates. If the returned index is 0, the tab is the first tab in the tab set, if the index is
+
1, the tab is the second tab, and so on. +
ItemAtPos is useful for determining which tab is located at a particular position in the tab
set control. +
Example +
The following code selects the tab that is at client coordinates (100, 10) in TabSet1.
TabSet1.TabIndex := TabSet1.ItemAtPos(Point(100, 10);
+
See also +
TabIndex property, Tabs property
+
ItemCount property +
Applies to I
TOutline component
Declaration
property ItemCount: Longint;
Run-time and read only. The ItemCount property specifies the total number of items in
an outline.
Example
The following code turns off automatic reindexing before inserting a new item into the
index if the index includes more than 100 items. Otherwise, automatic reindexing
remains active.
Outline1.SetUpdateState(Outline1.ItemCount > 100)
Outline1.Insert(1, ’NewItem’, MyData);
Outline1.EndUpdate
See also
Items property
ItemHeight property
Applies to
TComboBox, TDBComboBox, TDBListBox, TDirectoryListBox, TFileListBox, TListBox,
TOutline components
Declaration
property ItemHeight: Integer;
For list boxes, the ItemHeight property is the height of an item in the list box in pixels
when the list box’s Style property is lsOwnerDrawFixed. If the Style property is lsStandard
or lsOwnerDrawVariable, the value of ItemHeight is ignored. You can control the height of
an item in a fixed owner-draw list box by changing the height of ItemHeight.
For combo boxes, the ItemHeight property is the height of an item in the combo box list
in pixels when the combo box’s Style property is csOwnerDrawFixed. If the Style property
is any other setting, the value of ItemHeight is ignored. You can control the height of an
item in a fixed owner-draw combo box by changing the height of ItemHeight.
For outlines, the ItemHeight property is the height of an item in the outline in pixels
when the outline’s Style property is osOwnerDraw. If the Style property is osStandard, the
value of ItemHeight is ignored. You can control the height of an item in an owner-draw
outline by changing the height of ItemHeight.
Example
This example uses a list box and a button on a form. Enter as many strings in the list box
as you like using the property editor of the Items property in the Object Inspector. When
the user clicks the button on the form, the amount of vertical space allotted to each item
in the list box changes.
procedure TForm1.Button1Click(Sender: TObject);
begin
ListBox1.Style := lbOwnerDrawFixed;
ListBox1.ItemHeight := 30;
end;
See also
Items property, IntegralHeight property, OnDrawItem event
ItemIndex property
Applies to
TComboBox, TDBComboBox, TDBRadioGroup, TDirectoryListBox, TDriveComboBox,
TFileListBox, TFilterComboBox, TListBox, TRadioGroup components
Declaration
property ItemIndex: Integer;
Run-time only. The value of the ItemIndex property is the ordinal number of the selected
item in the control’s item list. If no item is selected, the value is -1, which is the default
value unless MultiSelect is True. To select an item at run time, set the value of ItemIndex
to the index of the item in the list you want selected, with 0 being the first item in the list.
For list boxes and combo boxes, if the value of the MultiSelect property is True and the
user selects more than one item in the list box or combo box, the ItemIndex value is the
index of the selected item that has focus. If MultiSelect is True, ItemIndex defaults to 0.
See also
+
Items property
+
ItemRect method +
Applies to
+
TDBListBox, TDirectoryListBox, TDrawGrid, TFileListBox, TListBox, TStringGrid, TTabSet
components I
Declaration
function ItemRect(Item: Integer): TRect;
The ItemRect method returns the rectangle that surrounds the item specified in the Item
parameter.
Example
This example uses a list box and four labels on a form. When the application runs, three
strings are added to the list box. When the user selects one of the strings in the list box,
the coordinates of the rectangle taken up by the selected string appear in the four labels:
procedure TForm1.FormCreate(Sender: TObject);
begin
with ListBox1 do
begin
Items.Add('Hello');
Items.Add('New');
Items.Add('World');
end;
end;
procedure TForm1.ListBox1Click(Sender: TObject);
var
ListBoxItem: TRect;
begin
ListBoxItem := ListBox1.ItemRect(ListBox1.ItemIndex);
Label1.Caption := ’Left ’ + IntToStr(ListBoxItem.Left);
Label2.Caption := 'Top ' + IntToStr(ListBoxItem.Top);
Label3.Caption := 'Right ' + IntToStr(ListBoxItem.Right);
Label4.Caption := 'Bottom ' + IntToStr(ListBoxItem.Bottom);
end;
See also
TRect type
Items property
Applies to
TFieldDefs, TIndexDefs, TList, TParams objects; TComboBox, TDBComboBox, TDBListBox,
TDBRadioGroup, TDirectoryListBox, TDriveComboBox, TFileListBox, TFilterComboBox,
TListBox, TMainMenu, TMenuItem, TOutline, TPopupMenu, TRadioGroup components
Example
This example uses an edit box, a list box, and a button on a form. When the user clicks
the button, the text in the edit box is added to the list box:
procedure TForm1.Button1Click(Sender: TObject);
begin
ListBox1.Items.Add(Edit1.Text);
end;
See also
Add method, Delete, method, Exchange method, Insert method, ItemIndex property, Move
method, Selected property
the subitem within the Items array. For example, if an application has a File drop-down
+
menu that contains the menu items New, Open, and Save, in that order,
FileMenu.Items[2] refers to the Save command. For menu items, Items is run-time only
+
property. +
For main menus, the Items property provides access to a menu item on the main menu
bar, and is available at both design time and run time. +
For pop-up menus, the Items property provides access to a menu item on the pop-up
menu, and is available at both design time and run time. +
Example +
The following code disables all the subitems of MenuItem1.
var
+
I: Integer;
begin +
I
for I := 0 to MenuItem1.ItemCount-1 do
MenuItem1.Items[I].Enabled := False;
end;
See also
Count property
For outlines
Declaration
property Items[Index: Longint]: TOutlineNode;
Run-time and read only. For outlines, the Items array property provides access to a
outline node by its row position. The value of the Index parameter corresponds to the
Index property and represents the position of the item within the Items array. For
example, if an outline has three items with Index property values of 1, 2, and 3 and Text
property values of ’Orange’, ’Apple’, and ’Banana’, respectively, Items[2] refers to the
’Apple’ item.
Example
The following code collapses the selected item of Outline1.
Outline1.Items[Outline1.SelectedItem].Expanded := False;
See also
SelectedItem property
Run-time only. The Items array property lets you access a specific pointer kept in the List
property of a list object. Using the Index parameter of Items you can access a list item by
its position in the list.
Example
This example creates a list object and inserts two records into it. The value of the record
fields are written on the form:
procedure TForm1.FormActivate(Sender: TObject);
type
PMyList = ^AList;
AList = record
I: Integer;
C: Char;
end;
var
MyList: TList;
ARecord: PMyList;
B: Byte;
Y: Word;
begin
MyList := TList.Create;
New(ARecord);
ARecord^.I := 100;
ARecord^.C := 'Z';
MyList.Add(ARecord); {Add integer 100 and character Z to list}
New(ARecord);
ARecord^.I := 200;
ARecord^.C := 'X';
MyList.Add(ARecord); {Add integer 200 and character X to list}
Y := 10; {Variable used in TextOut function}
{Go through the list until the end is reached}
for B := 0 to (MyList.Count - 1) do
begin
Y := Y + 30; {Increment Y Value}
ARecord := MyList.Items[B];
Canvas.TextOut(10, Y, IntToStr(ARecord^.I)); {Display I}
Y := Y + 30; {Increment Y Value again}
Canvas.TextOut(10, Y, ARecord^.C); {Display C}
end;
MyList.Free;
end;
See also
Add method, Expand method, First method, IndexOf method, Last method, Remove
method
Example
{ Assign 99999 to any integer parameter which does not have a value }
for I := 0 to Params.Count - 1 do
if (Params.Items[I].IsNull) and (Params.Items[I].DataType = ftInteger) then
{ Items is the default property, so you can omit its name }
Params[I].AsInteger := 99999;
See also
Count property
ItemSeparator property
Applies to
TOutline component
Declaration
property ItemSeparator: string;
The ItemSeparator property determines the separator string used between the outline
item Text values in the FullPath property of the TOutlineNode object. The default value of
ItemSeparator is ’\’.
For example, if the top-level outline item has a Text value of ’Animals’ and a child item
with the Text value of ’Dogs’, the FullPath property of the ’Dogs’ item would have the
value ’Animals\Dogs’ by default. If the string ’->’ were assigned to the ItemSeparator
property, the FullPath property of the ’Dogs’ item would be ’Animals->Dogs’.
Example
The following code changes the item separator to ’:’.
Outline1.ItemSeparator := ’:’;
See also
FullPath property, Text property, TOutlineNode object
KeepConnection property
Applies to
TDataBase component
Declaration
property KeepConnection: Boolean;
The KeepConnection property specifies whether an application remains connected to a
database server even when no tables are open. If an application needs to open and close
several tables in a single database, it will be more efficient to set KeepConnection to True.
That way, the application will remain connected to the database even when it does not
have any tables open. It can then open and close tables repeatedly without incurring the
overhead of connecting to the database each time. If KeepConnection is False, the database
must repeat the login process to the server each time the Connected property is set to
True.
The TSession component has an application-wide KeepConnections property that
determines the initial state of the KeepConnection property for temporary (automatically-
created) TDatabase components.
Example
Database1.KeepConnection := False;
See also
Session variable
KeyExclusive property
Applies to
TTable component
Declaration
property KeyExclusive: Boolean;
The KeyExclusive property indicates whether range and search functions will exclude
the matching records specified by the functions. KeyExclusive is False by default.
For the SetRangeStart and SetRangeEnd methods, KeyExclusive determines whether the
filtered range excludes the range boundaries. The default is False, which means rows
will be in the filtered range if they are greater than or equal to the start range specified
and less than or equal to the end range specified. If KeyExclusive is True, the methods
will filter strictly greater than and less than the specified values.
For the GotoNearest and FindNearest methods, KeyExclusive indicates whether a search
will position the cursor on or after the record being searched for. If KeyExclusive is False,
then GoToNearest and FindNearest will move the cursor to the record that matches the
specified values, if found. If True, then the methods will go the record immediately
following the matching record, if found.
Example
{ Limit the range from 1351 to 1356, excluding both 1351 and 1356 }
with Table1 do
begin
{ Set the beginning key }
EditRangeStart;
IndexFields[0].AsString := '1351';
{ Exclude 1351 itself }
KeyExclusive := True;
{ Set the ending key }
EditRangeEnd;
IndexFields[0].AsString := '1356';
{ Exclude 1356 itself }
KeyExclusive := True;
{ Tell the dataset to establish the range }
ApplyRange;
end;
See also
ApplyRange method, EditRangeStart method, EditRangeEnd method, KeyFieldCount
property
KeyFieldCount property
Applies to
TTable component
Declaration
property KeyFieldCount: Integer;
KeyFieldCount specifies the number of key fields to use with search functions (GotoKey,
FindKey, EditKey, and so on) if you don’t want to search on all the fields in the key.
See also
GotoKey method, GotoNearest method, EditKey method, FindKey method, FindNearest
method, SetKey method
The KeyPressed function returns True if a key has been pressed on the keyboard
+
The key can be read using the ReadKey function. +
Example +
uses WinCrt; +
+
begin
repeat
Write('Xx');
until KeyPressed;
end; +
See also +
ReadKey function
+
KeyPreview property +
Applies to K
TForm component
Declaration
property KeyPreview: Boolean;
When the KeyPreview property is True, most key events (OnKeyDown event, OnKeyUp
event, and OnKeyPress event) go to the form first, regardless of which control is selected
on the form. This allows your application to determine how to process key events. After
going to the form, key events are then passed to the control selected on the form. When
KeyPreview is False, the key events go directly to the controls. The default value is False.
The exceptions are the navigation keys, such as Tab, BackTab, the arrow keys, and so on.
If the selected control processes such keys, you can use KeyPreview to intercept them;
otherwise, you can’t.
If KeyPreview is False, all key events go to the selected control.
Example
This example changes a form’s color to aqua when the user presses a key, even when a
control on the form has the focus. When the user releases the key, the form returns to its
original color.
var
FormColor: TColor;
procedure TForm1.FormCreate(Sender: TObject);
begin
KeyPreview := True;
end;
procedure TForm1.FormKeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
begin
FormColor := Form1.Color;
Form1.Color := clAqua;
end;
procedure TForm1.FormKeyUp(Sender: TObject; var Key: Word;
Shift: TShiftState);
begin
Form1.Color := FormColor;
end;
KeyViolCount property
Applies to
TBatchMove component
Declaration
property KeyViolCount: Longint;
Run-time and read only. KeyViolCount reports the number of records which could not be
replaced, added, or deleted from Destination because of an integrity (key) violations. If
AbortOnKeyViol is True, KeyViolCount will never be greater than one, since the first
violation will cause the move to terminate.
Example
with BatchMove1 do
begin
Execute;
if KeyViolCount <> 0 then { something went wrong };
end;
KeyViolTableName property
Applies to
TBatchMove component
Declaration
property KeyViolTableName: TFileName;
KeyViolTableName, if specified, creates a local (Paradox) table containing all records from
the source table that caused an integrity violation (such as a key violation) as a result of
the batch operation.
If AbortOnKeyViol is True, then there will be at most one record in this table since the
operation will be aborted with that first record. KeyViolCount will have the number of
records placed in the new table.
Value Meaning
bkCustom You indicate which bitmap you want the bitmap button to have by setting the value of
the Glyph property to the bitmap of your choice. Like push buttons, you can either
select a ModalResult for the button, or you can supply the code to respond to an
OnClick event.
bkOK A green check mark and the text “OK” appears on the button face. The button
becomes the default button (the Default property is automatically set to True). When
the user chooses the button, the dialog box closes. The resulting ModalResult value of
the bitmap button is mrOK.
bkCancel A red X and the text “Cancel” appears on the button face. The button becomes the
Cancel button (the Cancel property is automatically set to True). When the user
chooses the button, the dialog box closes. The resulting ModalResult value of the
bitmap button is mrCancel.
bkYes A green check mark and the text “Yes” appears on the button face. The button
becomes the default button (the Default property is automatically set to True). When
the user chooses the button, any changes the user made in the dialog box are accepted
and the dialog box closes. The resulting ModalResult value of the bitmap button is
mrYes.
bkNo A red no symbol and the text “No” appears on the button face. The button becomes
the Cancel button (the Cancel property is automatically set to True). When the user
chooses the button, any changes the user made in the dialog box are canceled and the
dialog box closes. The resulting ModalResult value of the bitmap button is mrNo.
bkHelp A cyan question mark and the text “Help” appears on the button face. When the user
chooses the button, a Help screen in the application’s Help file appears. The Help file
that appears is the file specified as the value of the application’s HelpFile property. The
value of the HelpContext property of the button specifies which Help screen in the
Help file appears.
Value Meaning
bkClose A door with a green exit sign over it (use your imagination) and the text “Close”
appear on the button face. When the user chooses the button, the form closes. The
Default property of the button is True.
bkAbort A red X and the text “Abort” appears on the button face. The Cancel property of the
button is automatically set to True.
bkRetry A green circular arrow and the text “Retry” appear on the button face.
bkIgnore A green man walking away and the text “Ignore” appears on the button face. Use it to
allow the user to continue after an error has occurred.
bkAll A double green check mark and the text “Yes to All” appears on the button face. The
Default property of the button is automatically set to True.
Example
This example uses three bitmap buttons on a form. When the application runs, the Kind
property for each bitmap button is set, and the BitBtn1 button (the OK button) becomes
the default button.
procedure TForm1.FormCreate(Sender: TObject);
begin
BitBtn1.Kind := bkOK;
BitBtn2.Kind := bkCancel;
BitBtn3.Kind := bkHelp;
end;
See also
Cancel property, Default property, ModalResult property
Value Meaning
sbHorizontal Scroll bar is horizontal
sbVertical Scroll bar is vertical
For scroll bars of type TControlScrollBar (form and scroll box scroll bars accessed
through the HorzScrollBar and VertScrollBar properties), Kind is a read- and run-time-
only property.
Example
This example uses a radio group box and a scroll bar on a form. When the user selects
one of the radio buttons, the scroll bar changes orientation accordingly.
procedure TForm1.FormCreate(Sender: TObject);
Example
This code determines that when the user clicks the scroll bar on either side of the scroll
box, the scroll box moves 100 positions on the scroll bar:
ScrollBar1.LargeChange := 100;
See also
Max property, Min property, Position property, SmallChange property
Last method
Applies to
TList object; TQuery, TStoredProc, TTable components
Example
This example inserts two records into a list object and displays the contents of the last
record in the list on the form:
procedure TForm1.FormActivate(Sender: TObject);
type
PMyList = ^AList;
AList = record
I: Integer;
C: Char;
end;
var
MyList: TList;
ARecord: PMyList;
begin
MyList := TList.Create;
New(ARecord);
ARecord^.I := 100;
ARecord^.C := 'Z';
MyList.Add(ARecord); {Add integer 100 and character Z to list}
New(ARecord);
ARecord^.I := 200;
ARecord^.C := 'X';
MyList.Add(ARecord); {Add integer 200 and character X to list}
ARecord := MyList.Last;
Canvas.TextOut(10, 10, IntToStr(ARecord^.I)); {Display I}
Canvas.TextOut(10, 40, ARecord^.C); {Display C}
MyList.Free;
end;
See also
Capacity property, First method, IndexOf method, Items property
If the dataset is in Insert or Edit state, Last will perform an implicit Post of any pending
+
data. +
Example +
Table1.Last;
+
See also
First method, MoveBy method, Next method, Prior method, SetRangeEnd method +
Layout property
+
+
Applies to
TBitBtn, TSpeedButton components +
Declaration +
property Layout: TButtonLayout;
The Layout property determines where the image appears on the bitmap button or a
+
speed button. These are the possible values:
L
Value Meaning
blGlyphLeft The image appears near the left side of the button.
blGlyphRight The image appears near the right side of the button.
blGlyphTop The image appears near the top of the button.
blGlyphBottom The image appears near the bottom of the button.
Example
This example uses a bitmap button on a form that has a bitmap specified as the value of
its Glyph property. When the user clicks the bitmap button, the bitmap randomly
changes its position on the button:
procedure TForm1.BitBtn1Click(Sender: TObject);
begin
Randomize;
case Random(4) of
0: BitBtn1.Layout := blGlyphLeft;
1: BitBtn1.Layout := blGlyphRight;
2: BitBtn1.Layout := blGlyphTop;
3: BitBtn1.Layout := blGlyphBottom;
end;
end;
See also
Margin property, Spacing property
Left property
Applies to
All controls; TFindDialog, TReplaceDialog components
Declaration
property Left: Integer;
The Left property determines the horizontal coordinate of the left edge of a component
relative to the form in pixels. For forms, the value of the Left property is relative to the
screen in pixels. The default value is -1.
The Left property for the Find and Replace dialog boxes is available at run-time only.
Example
The following example moves the button 10 pixels to the right each time a user clicks it:
procedure TForm1.Button1Click(Sender: TObject);
begin
Button1.Left := Button1.Left + 10;
end;
See also
SetBounds method, Top property
LeftCol property
Applies to
TDrawGrid, TStringGrid components
Declaration
property LeftCol: Longint;
Run-time only. The LeftCol property determines which column in the grid appears at the
far left side of the grid.
If you have one or more nonscrolling columns in the grid, they remain at the far left,
regardless of the value of the LeftCol property. In this case, the column you specify as the
far left column is the first column to the immediate right of the nonscrolling columns.
Example
This line of code positions the fourth column of a string grid at the left edge of the grid:
StringGrid1.LeftCol := 3;
See also
FixedCols property, TopRow property
Declaration
property Length: Longint;
Run-time and read only. The Length property specifies the length of the medium in the
open multimedia device. Length is specified using the current time format, which is
specified by the TimeFormat property.
Example
The following code sets Wait to False if the Length of the media is over 10,000. If
TimeFormat is tfMilliseconds, Wait is set to False if the media is over 10 seconds long.
MediaPlayer1.Wait := (MediaPlayer1.Lenth > 10000);
See also
Position property, Start property, TrackLength property
Level property
Applies to
TOutlineNode object
Declaration
property Level: Word;
Run-time and read only. The Level property indicates the level of indentation of an item
within the TOutline component. The value of Level is 1 for items on the top level. The
value of Level is 2 for their children, and so on.
Example
The following code tests to determine if the fifth outline item is on the same level as the
selected outline item.
if Outline1.Items[5].Level = Outline1.Items[Outline1.SelectedItem].Level then
{ The selected item is on the same level as the fifth item };
See also
ChangeLevelBy method, TopItem property
Lines property
Applies to
TDBMemo, TDDEClientItem, TDDEServerItem, TMemo, TOutline components
Declaration
property Lines: TStrings;
The Lines property contains the text lines in a memo component.
For a database memo control, the Lines property is a run-time property only.
Example
This example uses a button and a memo control on a form. When the user clicks the
button, the contents of the system’s AUTOEXEC.BAT file is loaded into the memo, and
the sixth line of the file is written across the top of the form.
procedure TForm1.Button1Click(Sender: TObject);
begin
Memo1.Lines.LoadFromFile('C:\AUTOEXEC.BAT');
Writeln('The 6th line of AUTOEXEC.BAT is: ', Memo1.Lines[5]);
end;
See also
GetTextBuf method, SetTextBuf method, Text property
Declaration
property Lines: TStrings;
The Lines property contains the text data to exchange in a DDE conversation. For
TDDEClientItem components, Lines specifies the text that is updated by the DDE server
application. For TDDEServerItem components, Lines specifies the text that is sent to any
DDE clients when the value of Lines changes or when a client requests to be updated.
When Lines is changed, an OnChange event occurs.
Lines corresponds to the Text property. Whenever the value of Lines or Text is changed,
the other is updated so that the first line of Lines is always equal to Text. Use Lines to
contain text values longer than 255 characters (which is the limit of the Text property).
For shorter strings, use the Text property.
If the Lines property is of a TDDEClientItem component, you can also send the text in
Lines directly to the DDE server by poking data with the PokeDataLines method.
If the Lines property is of a TDDEServerItem component, the DDE client can change Lines
by poking data. The poked data replaces the contents of Lines and an OnChange event
occurs.
Example
The following code assigns the value to the Lines property of DDEClientItem1 to the
Lines of Memo1. This code is executed in the OnChange event handler of
DDEClientItem1, so whenever the client is updated, the new data from the server is
displayed.
procedure TForm1.DdeClientItem1Change(Sender: TObject);
begin
Memo1.Lines := DDEClientItem1.Lines
end;
LineTo method
Applies to
TCanvas object
Declaration
procedure LineTo(X, Y: Integer);
The LineTo method draws a line on the canvas from the current drawing position
(specified by the PenPos property) to the point specified by X and Y and sets the pen
position to (X, Y).
Example
The following code draws a line from the upper left corner of a form to the point clicked
with the mouse.
procedure TForm1.FormMouseDown(Sender: TObject; Button: TMouseButton;
Shift: TShiftState; X, Y: Integer);
begin
Canvas.MoveTo(0, 0);
Canvas.LineTo(X, Y);
end;
See also
MoveTo method
LinksDlg displays the Links dialog box. Use the Links dialog box to view and edit the
+
current OLE links in your application. These are the parameters of LinksDlg: +
Field
Form
Description
The form that owns the Links dialog box.
+
HelpContext A Help context ID number to be used if the user chooses Help from within the Links
dialog box. If you pass 0 for HelpContext, no Help button appears in the Links dialog
+
box. Pass a number other than 0 if you want to provide context-sensitive online Help.
+
Example
The following code activates the Links dialog with a context-sensitive Help ID number +
of 1000.
LinksDlg(Form1, 1000);
+
See also +
InsertOLEObjectDlg function, LinksDlgEnabled function, PasteSpecialDlg function
+
LinksDlgEnabled function Toctrl +
Declaration L
function LinksDlgEnabled(Form: TForm): Boolean;
LinksDlgEnabled determines if the Links dialog box is enabled. If so, LinksDlgEnabled
returns True and LinksDlg can be successfully called. If not, LinksDlgEnabled returns False
and nothing happens if you call LinksDlg.
The Form parameter specifies the form that owns the Links dialog box.
Example
The following code activates the Links dialog box if it is enabled.
if LinksDlgEnabled(Form1) then LinksDlg(Form1, 0);
List property
Applies to
TList object
Declaration
property List: PPointerList;
Run-time and read only. The List property stores a list of pointers that reference objects
of any type. The declaration of PPointerList is
PPointerList = ^TPointerList;
Example
The following code creates List1 and Object1, then adds Object1 to List1. If the first item
in the List property List1 differs from the first item of the Items property of List1 (which
shouldn’t happen), a message is displayed.
var
List1: TList;
Object1: TObject;
begin
List1 := TList.Create;
Object1 := TObject.Create;
List1.Add(Object1);
if List1.List^[0]<>List1.Items[0] then
MessageDlg('Something is wrong here', mtInformation, [mbOK], 0);
List1.Free;
Object1.Free;
end;
See also
FileEditStyle property, TStrings object
Ln function System
Declaration
function Ln(X: Real): Real;
The Ln function returns the natural logarithm (Ln(e) = n) of the real-type expression X.
Example
var
e : real;
S : string;
begin
e := Exp(1.0);
Str(ln(e):3:2, S);
S := 'ln(e) = ' + S;
Canvas.TextOut(10, 10, S);
end;
See also
Exp function
Example
This example uses a bitmap button on a form. When the application runs and the form is
created, a bitmap is placed on the bitmap button:
procedure TForm1.FormCreate(Sender: TObject);
begin
BitBtn1.Glyph.LoadFromFile('TARTAN.BMP');
end;
See also
SaveToFile method, Strings property
Example
{ Load a blob field with the contents of autoexec.bat }
BlobField1.LoadFromFile(‘c:\autoexec.bat’);
LoadFromStream method
Applies to
TBlobField, TGraphicField, TMemoField components
Declaration
procedure LoadFromStream(Stream: TStream);
The LoadFromStream method reads Stream and stores the contents in TBlobField,
TMemoField or TGraphicField.
Note For a TMemoField or TGraphicField, the file should have been created by the SaveToFile or
SaveToStream method.
Example
{ Load a blob field from an existing STream1 }
BlobField1.LoadFromStream(Stream1);
See also
LoadFromFile method, SaveToStream method
LoadMemo method
Applies to
TDBMemo component
Declaration
procedure LoadMemo;
The LoadMemo method loads a text BLOB into the database memo control. If the value of
+
the AutoDisplay property is False, the text of a memo is not automatically loaded. If
AutoDisplay is False, you can control when the text is loaded at run time by calling
+
LoadMemo when you want the text to appear in the control. +
Example
This example uses a database memo that is connected to a BLOB text field in the dataset.
+
It also contains a button. When the user clicks the button, the BLOB loads into the
memo. +
procedure TForm1.FormCreate(Sender: TObject);
begin
+
DBMemo1.AutoDisplay := False;
end; +
procedure TForm1.Button1Click(Sender: TObject);
begin +
DBMemo1.LoadMemo;
end; +
See also
LoadPicture method
+
L
LoadPicture method
Applies to
TDBImage component
Declaration
procedure LoadPicture;
The LoadPicture method loads the image specified as the value of the Picture property
into the database image control.
If the value of the AutoDisplay property is False, the image of a database image control is
not automatically loaded. If AutoDisplay is False, you can control when the image is
loaded at run time by calling LoadPicture when you want the image to appear in the
control.
Example
The following code loads the picture into DBImage1.
DBImage1.LoadPicture;
See also
LoadMemo method
Local property
Applies to
TQuery component
Declaration
property Local: Boolean;
Run-time and read only. The Local property specifies if the table referenced by the
TQuery is a local dBASE or Paradox table or an SQL server table. If Local is True, then the
table is a dBASE or Paradox table. If Local is False, the table is a SQL table.
For remote SQL tables, some operations (such as record counts) may take longer than
for local tables, owing to network constraints.
Example
{ If the table is local, allow the data-aware controls to display the changes }
DataSource1.Enabled := Query1.Local;
Locale property
Applies to
TDataBase, TTable, TQuery, TSession, TStoredProc components
Locked property
Applies to
TPanel component
Declaration
property Locked: Boolean;
The Locked property determines whether a panel is replaced by an in-place active OLE
object. If Locked is False, the OLE server can replace the panel. If Locked is True and the
panel is aligned to one of the edges of the form (its Align property is alTop, alBottom,
alLeft, or alRight), then the panel remains when an OLE object in a TOLEContainer
component is activated in place.
Use Locked to prevent status bars and the like from being replaced.
Example
The following code sets Locked to True for a panel named StatusBar.
StatusBar.Locked := True;
See also
InPlaceActive property
LoginPrompt property
Applies to
TDataBase component
Declaration
property LoginPrompt: Boolean;
The LoginPrompt property is used to control how security is handled for SQL databases.
If True, (the default), the standard Delphi Login dialog box will be opened when the
application attempts to establish a database connection. The user must then enter a
proper user name and password to connect to a database on the server.
If False, then an application will look for login parameters in the Params property of the
TDatabase component. These are the USERNAME and PASSWORD parameters. For
example,
USERNAME = SYSDBA
PASSWORD = masterkey
This is generally not recommended since it compromises server security.
Example
{ Do not display the login prompt }
Database1.LoginPrompt := False;
See also
OnLogin event
LongRec SysUtils
Declaration
LongRec = record
Lo, Hi: Word;
end;
LongRec declares a utility record that stores the high and low order bytes of the specified
variable as type Word.
LongRec is useful in handling double-word length variables.
See also
Hi function, Lo function
See also
LookupField property, Options property
LookupField property
Applies to
TDBLookupCombo, TDBLookupList components
Declaration
property LookupField: string;
The LookupField property links the dataset the database lookup combo box or database
lookup list box uses to “look up” data to the primary dataset you are working with.
Although the name of the field specified as the LookupField does not have to be the same
as the name of the field specified as the DataField, the two fields must contain the same
values. For example, the LookupField value can be CustomerNumber and the DataField
value can be CustNo, as along as both fields use the same number to identify a particular
customer. When you specify a LookupField, the current value of that field appears in the
control, if the Active property of both datasets is True.
After you specify a LookupField field, you can choose which field you prefer to display in
the control with the LookupDisplay property.
Example
The following code designates that DBLookupCombo1 looks up data in the
’CustomerNumber’ field.
DBLookupCombo1.LookupField := ’CustomerNumber’;
See also
DataSource property, LookupSource property
LookupSource property
Applies to
TDBLookupCombo, TDBLookupList components
Declaration
property LookupSource: TDataSource;
The LookupSource of a database lookup combo box or lookup list box is the data source
component (TDataSource) that identifies the dataset you want the control to use to “look
up” the information you want displayed in the control.
Example
The following code specifies that DataSource1 is the lookup source for DBLookupCombo1.
DBLookupCombo1.LookupSource := DataSource1;
See also
LookupDisplay property, LookupField property
See also
High function
Example
This example uses two edit boxes and a button on a form. When the user clicks the
button, the text in the Edit1 edit box displays in the Edit2 edit box in lowercase letters.
procedure TForm1.Button1Click(Sender: TObject);
begin
Edit2.Text := LowerCase(Edit1.Text);
end;
See also
AnsiLowerCase function, UpperCase function
MainForm property
Applies to
TApplication component
Declaration
property MainForm: TForm;
Run-time and read only. The MainForm property identifies which form in the
application is the main form, which is the form that is always created first. When the
main form closes, the application terminates.
When you create a new project, Form1 automatically becomes the value of the MainForm
property. If you want to make another form become the main form, use the Forms page
of the Options|Project Options dialog box.
See also
Application variable, CreateForm method, Run method
Mappings property
Applies to
TBatchMove component
Declaration
property Mappings: TStrings;
By default TBatchMove matches columns based on their position in the source and
destination tables. That is, the first column in the source is matched with the first column
in the destination, and so on.
To override the default column mappings, use the Mappings property. This is a list of
column mappings (one per line) in one of two forms. To map the column ColName in
the source table to the column of the same name in the destination table use:
See also
Source property
Margin property
Applies to
TBitBtn, TControlScrollBar, TSpeedButton components
Declaration
property Margin: Integer;
The Margin property determines the number of pixels between the edge of the image
(specified in the Glyph property) and the edge of the button. The edges that the margin
separates depends on the layout of the image and text (specified in the Layout property).
For example, if Layout is blGlyphLeft, the margin appears between the left edge of the
image and the left edge of the button. If Margin is 3, three pixels separates the image and
the button edges. If Margin is 0, no distance in pixels separates the image and the button
edges.
If Margin is -1 (which it is by default), then the image and text (specified in the Caption
property) are centered. The number of pixels between the image and button edge is
equal to the number of pixels between the opposite edge of the button and the text.
Example
This example uses a moderately large bitmap button on a form. When the application
runs, a bitmap (or glyph) is loaded on to the button, the bitmap appears on the right side
of the button, and bitmap is placed 30 pixels from the right edge of the bitmap button.
procedure TForm1.FormCreate(Sender: TObject);
begin
with BitBtn1 do
begin
Glyph.LoadFromFile('C:WINDOWS\CARS.BMP');
Layout := blGlyphRight;
Margin := 30;
end;
end;
See also
Caption property, Glyph property, Layout property
Declaration
procedure Margin: Word;
The Margin property value is the minimum number of pixels you want controls on a
form or in a scroll box to be from the edge of the form or scroll box. This number is
automatically added to the Range value to ensure that the user has a scroll bar whenever
the distance from a control and the edge of the form or scroll box becomes less than the
Margin value.
The default value is 0.
Example
This example uses a button and a label on a form. Place the label near the left side of the
form, and place the button somewhere near the middle of the form. When the user runs
the application, a horizontal scroll bar does not appear, because no control on the form is
close enough to the right edge. Each time the user clicks the button, the button moves 25
pixels to the right, and the calculated Range value is reported in the caption of the label.
Repeatedly clicking the button eventually moves the button close enough to the edge of
the form (within the Margin amount) so that a horizontal scroll bar appears:
Example
This example uses a filter combo box and a label on a form. When the user selects a filter
in the filter combo box, the selected mask appears in the caption of the label:
procedure TForm1.FilterComboBox1Change(Sender: TObject);
begin
Label1.Caption := 'The selected mask is ' + FilterComboBox1.Mask;
end;
procedure TForm1.FormCreate(Sender: TObject);
begin
FilterComboBox1.Filter := 'All files (*.*)|*.*| Pascal files (*.pas)|*.pas';
end;
See also
Filter property
Example
This example uses a file list box on a form. When the application runs, the list box
displays only files with a .PAS file extension:
procedure TForm1.FormCreate(Sender: TObject);
begin
FileListBox1.Mask := '*.PAS';
end;
See also
Filter property
MasterFields property
Applies to
TTable component
Declaration
property MasterFields: string;
Use the MasterFields property to specify the column(s) to link a detail table with a master
table that is specified by the MasterSource property. MasterFields is a string consisting of
one or more column names that join the two tables. Separate multiple column names
with semicolons. Each time the current record in the master table changes, the new
values in those fields are used to select corresponding records from the detail table for
display. At design time, use the Field Link Designer to set this property.
Example
Suppose you have a master table named Customer that contains a CustNo field, and you
also have a detail table named Orders that also has a CustNo field. To display only those
records in Orders that have the same CustNo value as the current record in Customer,
write this code:
Max property
Applies to
TScrollBar component
Declaration
property Max: Integer;
The Max property along with the Min property determines the number of possible
positions the scroll box can have on the scroll bar. The LargeChange and SmallChange
properties use the number of positions to determine how far to move the scroll box
when the user uses the scroll bar.
For example, if Max is 30000 and Min is 0, the scroll box can assume 30,000 positions on
a horizontal scroll bar. If the LargeChange property setting is 10000 and the scroll box
position is at the far left of the scroll bar (Position is 0), the user can click the scroll bar
three times to the right of the scroll box before the scroll box is moved all the way to the
right of the scroll bar (30000/10000 = 3).
If you want to change the Min, Max, and Position values all at once at run time, call the
SetParams method.
Example
This code changes the maximum position of the scroll bar from 100, the default value, to
30000:
ScrollBar1.Max := 30000;
See also
LargeChange property, Min property, Position property, SetParams method, SmallChange
property
Example
uses Dialogs;
type
FriendRec = record
Name: string[30];
Age: Byte;
end;
var
P: Pointer;
begin
if MaxAvail < SizeOf(FriendRec) then
MessageDlg('Not enough memory', mtWarning, [mtOk], 0)
else
begin
{ Allocate memory on heap }
GetMem(P, SizeOf(FriendRec));
{ ... }
end;
end;
See also
MinFontSize property
MaxLength property
Applies to
TComboBox, TDBEdit, TDBLookupCombo, TDBMemo, TEdit, TMaskEdit, TMemo
components
Declaration
property MaxLength: Integer;
The MaxLength property specifies the maximum number of characters the user can enter
in an edit box, memo, or combo box. The default setting for MaxLength is 0, which
means that there is no limit on the number of characters the control can contain. Any
other number limits the number of characters the control accepts.
Example
The following example sets the maximum number of characters for an edit box to 80:
Edit1.MaxLength := 80;
MaxPage property
Applies to
TPrintDialog component
Declaration
property MaxPage: Integer;
The MaxPage property determines the greatest page number the user can use when
specifying pages to print. If the user specifies a number greater than the value in
MaxPage, a warning message appears and the user must enter a valid number or close
the dialog box. The default value is 0.
Note The user can specify pages numbers only if the Options property set includes the value
poPageNums.
Example
This example uses a button and a Print dialog box on a form. When the user clicks the
button, the code makes page four the highest page number the user can select in the
Print dialog box and displays the dialog box:
procedure TForm1.Button1Click(Sender:TObject);
begin
PrintDialog1.Options := [poPageNums];
PrintDialog1.ToPage := 4;
PrintDialog1.MaxPage := 4;
if PrintDialog1.Execute then
...;
end;
See also
MinPage property
MaxRecords property
Applies to
TReport component
Declaration
property MaxValue: Longint;
The MaxValue property limits the maximum value in the field. Assigning a value greater
than MaxValue raises an exception.
Example
{ Limit a field to 1 to 10}
Field1.MaxValue := 10;
Field1.MinValue := 1;
See also
MinValue property
MDIChildCount property
Applies to
TForm component
Declaration
property MDIChildCount: Integer;
Run-time and read only. The value of the MDIChildCount property is the number of
child windows open in an MDI application.
Example
The following code closes Form1 if it has no MDI children open.
if Form1.MDIChildCount = 0 then Form1.Close;
See also
ActiveMDIChild property, FormStyle property, MDIChildren property
MDIChildren property
Applies to
TForm component
Declaration
property MDIChildren[I: Integer]: TForm;
Run-time and read only. The MDIChildren property array provides access to a child
window or form in an MDI application through an index value, I. The value of I is
determined by the order in which the window was created. For example, the first MDI
child window has an I value of 0.
Example
The following code closes all the MDI children of Form1.
var
I: Integer;
begin
with Form1 do
for I := 0 to MDIChildCount-1 do
MDIChildren[I].Close;
end;
See also
FormStyle property, MDIChildCount property
Example
This code displays a new menu named NewMenu when the user clicks the button
ChangeMenu button.
procedure TForm1.ChangeMenuClick(Sender: TObject);
begin
Menu := NewMenu;
end;
Merge method
Applies to
TMainMenu component
Declaration
procedure Merge(Menu: TMainMenu);
The Merge method merges a main menu of one form with a main menu of another for
non-MDI applications. For example, when your application uses the main menu of the
first form as the main menu for the application, and your application displays a second
form, you can call Merge to merge the main menu on the second form with the main
menu of the application.
Specify the menu you want merged with this menu as the Menu parameter.
Depending on the value of the GroupIndex property of menu items on the main menu,
the merged menu items can replace menu items on the menu bar, or add or insert menu
items into the menu bar. See GroupIndex for information on how to do these things.
It you want merging and unmerging to occur automatically when another form is
displayed, change the value of the AutoMerge property to True.
Example
This example uses two forms, each containing a main menu created with the Menu
Designer. It also uses a button on Form1. When the user clicks the button, Form2 appears
and the main menu of Form2 merges with that of Form1.
Before running this example, add Unit2 to the uses clause of Unit1.
procedure TForm1.Button1Click(Sender: TObject);
begin
Form2.Show;
MainMenu1.Merge(Form2.MainMenu1);
end;
See also
AutoMerge property, Unmerge method
MessageBox method
Applies to
TApplication component
Declaration
function MessageBox(Text, Caption: PChar; Flags: Word): Integer;
The MessageBox method is an encapsulation of the Windows API MessageBox function
except that you don’t need to supply a window handle.
The MessageBox method displays a generic dialog box that displays a message and one
or more buttons. The value of the Text parameter is the message, which can be longer
than 255 characters if necessary. Long messages are automatically wrapped in the
message box. The value of the Caption property is the caption that appears in the title bar
of the dialog box. Captions can be longer than 255 characters, but they don’t wrap. A
long caption results in a wide message box.
To see the possible values of the Flags parameter, see the MessageBox function in the
Windows API Help file (WinAPI.HLP). The corresponding parameter on that Help
screen is called TextType. The values determine the buttons that appear in the message
box and the behavior of the message box. The values can be combined to obtain the
+
effect your want. +
The return value of the MessageBox method is 0, if there wasn’t enough memory to
create the message box, or one of these values:. +
Value Numeric value Meaning +
IDABORT
IDCANCEL
3
2
The user chose the Abort button
The user chose the Cancel button +
IDIGNORE
IDNO
5
7
The user chose the Ignore button
The user chose the No button +
IDOK
IDRETRY
1
4
The user chose the OK button
The user chose the Retry button +
IDYES 6 The user chose the Yes button
+
Example
This example uses a button and a label on a form. When the user clicks the button, a +
message box appears. When the user responds to the message box, the button selected is
reported in the caption of the label: +
procedure TForm1.Button1Click(Sender: TObject);
var
Button: Integer;
+
begin
Button := Application.MessageBox('Welcome to Delphi!', 'Message Box', mb_OKCancel +
M
mb_DefButton1);
if Button = IDOK then
Label1.Caption := 'You chose OK';
if Button = IDCANCEL then
Label1.Caption := 'You chose Cancel';
end;
See also
MessageDlg function, MessageDlgPos function, ShowMessage procedure, ShowMessagePos
procedure
The AType parameter determines the type of message box that appears. These are the
possible values:
Value Meaning
mtWarning A message box containing a yellow exclamation point symbol.
mtError A message box containing a red stop sign.
mtInformation A message box containing a blue “i”.
mtConfirmation A message box containing a green question mark.
mtCustom A message box containing no bitmap. The caption of the message box is the name of
the application’s executable file.
The AButtons parameter determines which buttons appear in the message box. AButtons
is of type TMsgDlgBtns, which is a set, so you can include multiple buttons within the
set. These are the values you can include in the set:
Value Meaning
mbYes A button with a green check mark and the text ‘Yes’ on its face
mbNo A button with a red circle and slash mark through the circle and the text ‘No’ on its face
mbOK A button with a green check mark and the text ‘OK’ on its face
mbCancel A button with a red X and the text ‘Cancel’ on its face
mbHelp A button with a cyan question mark and the text ‘Help’ on its face
mbAbort A button with a red check mark and the text ‘Abort’ on its face
mbRetry A button with two green circular arrows and the text ‘Retry’ on its face
mbIgnore A button with a green man walking away and the text ‘Ignore’ on its face
mbAll A button with a green double check marks and the text ‘All’ on its face
In addition to the individual set values, VCL defines three constants that are predefined
sets that include common button combinations:
Value Meaning
mbYesNoCancel A set that puts the Yes, No, and Cancel buttons in the message box
mbOkCancel A set that puts the OK and Cancel buttons in the message box
mbAbortRetryIgnore A set that puts an Abort, Retry, and Ignore buttons in the message box
When using these constants, remember not to add the brackets [ ] to define the set. These
constants are already predefined sets.
The HelpCtx parameter determines which Help screen is available for the message box.
For more information about Help context values, see the HelpContext property.
The function returns the value of the button the user selected. These are the possible
return values:
See also
Kind property, MessageDlgPos function, ModalResult property, MessageBox method,
ModalResult property, ShowMessage procedure, ShowMessagePos procedure
Value Meaning
mtWarning A message box containing yellow exclamation point symbol.
mtError A message box containing a red stop sign.
mtInformation A message box containing a blue “i”.
mtConfirmation A message box containing a green question mark.
mtCustom A message box containing no bitmap. The caption of the message box is the
name of the application’s executable file.
The AButtons parameter determines which buttons appear in the message box. AButtons
is of type TMsgDlgBtns, which is a set, so you can include multiple buttons within the
set. These are the values you can include in the set:
Value Meaning
mbYes A button with a green check mark and the text ‘Yes’ on its button face
mbNo A button with a red circle and slash mark through the circle and the text ‘No’ on its button
face
mbOK A button with a green check mark and the text ‘OK’ on its button face
mbCancel A button with a red X and the text ‘Cancel’ on its button face
mbHelp A button with a cyan question mark and the text ‘Help’ on its button face
mbAbort A button with a red check mark and the text ‘Abort’ on its face
mbRetry A button with two green circular arrows and the text ‘Retry’ on its face
mbIgnore A button with a green man walking away and the text ‘Ignore’ on its face
mbAll A button with a green double check marks and the text ‘All’ on its face
In addition to the individual set values, VCL defines three constants that are predefined
sets which include common button combinations:
Value Meaning
mbYesNoCancel A set that puts the Yes, No, and Cancel buttons in the message box
mbOkCancel A set that puts the OK and Cancel buttons in the message box
mbAbortRetryIgnore A set that puts an Abort, Retry, and Ignore buttons in the message box
When using these constants, remember not to add the brackets [ ] to define the set. These
constants are already predefined sets.
The HelpCtx parameter determines which Help screen is available for the message box.
+
For more information about Help context values, see the HelpContext property. +
The X and Y integer parameters are the screen coordinates in pixels where the top left
corner of the message box appears. +
The function returns the value of the button the user selected. These are the possible
return values: +
Return values +
mrNone
mrOk
mrAbort
mrRetry
mrYes
mrNo
+
mrCancel mrIgnore mrAll
+
The MsgDlgButtonStyle constant in the Dialogs unit is declared like this:
MsgDlgButtonStyle: TButtonStyle = bsAutoDetect;
+
This ensures that the style of the buttons matches the style used by the operating
environment your application is running under. If you prefer to always use a particular
+
style, change the value of the MsgDlgButtonStyle. See the Style property for bitmap
buttons for the possible values and their meanings.
+
The MsgDlgGlyphs typed constant in the Dialogs unit is declared like this: +
MsgDlgGlyphs: Boolean = True;
This declaration ensures that bitmaps (or glyphs) appear on the message dialog box
M
buttons. If you prefer that the bitmaps are not present, change the value of
MsgDlgButtonStyle to False.
Example
This example displays a confirmation style message box at screen coordinates 125, 25
that asks users if they want to color the form green. If the user chooses Yes, the form
turns bright green:
procedure TForm1.Button1Click(Sender: TObject);
var
ButtonSelected: Word;
begin
if MessageDlgPos(‘Color the form green?', mtConfirmation,
[mbYes, mbNo], 0, 125, 25) := mrYes then
Color := clLime;
end;
This example uses a button on a form. When the user clicks the button, a message box
appears with a Yes, No, and Cancel button on it:
procedure TForm1.Button1Click(Sender: TObject);
begin
MessageDlgPos('Are you there?', mtConfirmation, mbYesNoCancel, 0, 200, 200);
end;
See also
Kind property, MessageBox method, MessageDlg function, ModalResult property,
ShowMessage procedure, ShowMessagePos procedure
Metafile property
Applies to
TPicture object
Declaration
property Metafile: TMetafile
The Metafile property specifies the contents of the TPicture object as a Windows metafile
graphic (.WMF file format). If Metafile is referenced when the TPicture contains a Bitmap
or Icon graphic, the graphic won’t be converted. Instead, the original contents of the
TPicture are discarded and Metafile returns a new, blank metafile.
Example
The following line of code displays the pixels-per-inch of the coordinate mapping of a
metafile. The Inch property of the metafile stored in the MyGraphic is converted to text
and assigned to the Caption of Label1.
Label1.Caption := IntToStr(MyGraphic.Metafile.Inch);
See also
Graphic property
Min property
Applies to
TScrollBar component
Declaration
property Min: Integer;
The Min property along with the Max property determines the number of possible
positions the scroll box can have on the scroll bar. The LargeChange and SmallChange
properties use the number of positions to determine how far to move the scroll box
when the user uses the scroll bar.
For example, if Max is 3000 and Min is 0, the scroll box can assume 3000 positions on a
horizontal scroll bar. If the LargeChange property setting is 1000 and the scroll box
position is at the far left of the scroll bar (Position is 0), the user can click the scroll bar
three times to the right of the scroll box before the scroll box is moved all the way to the
right of the scroll bar (3000/1000 = 3).
If you want to change the Min, Max, and Position values all at run time, call the
+
SetParams method. +
Example
The following code sets the minimum position to the value specified in an edit box, and
+
sets the maximum position to 1000 more than the minimum position. +
+
ScrollBar1.Min := StrToInt(Edit1.Text);
ScrollBar1.Max := ScrollBar1.Min + 1000;
See also
LargeChange property, Max property, Position property, SetParams method, SmallChange
+
property +
MinFontSize property +
Applies to
+
TFontDialog component
+
Declaration
property MinFontSize: Integer;
+
The MinFontSize property determines the smallest font size available in the Font dialog M
box. Use the MinFontSize property when you want to limit the font sizes available to the
user. To limit the font sizes available, the Options set property of the Font dialog box
must also contain the value fdLimitSize. If fdLimitSize is False, setting the MinFontSize
property has no affect on number of fonts available in the Font dialog box.
The default value is 0, which means there is no minimum font size specified.
Example
This example uses a Font dialog box, a button, and a label on a form. When the user
clicks the button, the Font dialog box appears. The font sizes available are within the
range of 10 to 14. When the user chooses OK, the selected font is applied to the caption
of the label.
procedure TForm1.Button1Click(Sender: TObject);
begin
FontDialog1.Options := [fdLimitSize];
FontDialog1.MaxFontSize := 14;
FontDialog1.MinFontSize := 10;
if FontDialog1.Execute then
Label1.Font := FontDialog1.Font;
end;
See also
MinFontSize property
Minimize method
Applies to
TApplication component
Declaration
procedure Minimize;
The Minimize method shrinks your application into an icon on your Windows desktop.
Example
This example uses a button named Shrink on a form. When the user clicks the button, the
application minimizes to an icon:
procedure TForm1.ShrinkClick(Sender: TObject);
begin
Application.Minimize;
end;
See also
Application variable, Icon property
MinPage property
Applies to
TPrintDialog component
Declaration
property MinPage: Integer;
The MinPage property determines the smallest page number the user can use when
specifying pages to print. If the user specifies a number less than the value of MinPage, a
warning message appears and the user must enter a valid number or close the dialog
box. The default value is 0.
Note The user can specify pages numbers only if the Options property set includes the value
poPageNums.
Example
This example uses a button and a Print dialog on a form. When the user clicks the
button, the code sets the lowest and the highest possible page numbers the user can
select and displays the dialog box:
procedure TForm1.Button1Click(Sender: TObject);
begin
with PrintDialog1 do
begin
See also
MaxValue property
Example
uses Dialogs;
begin
{$I–}
{ Get directory name from TEdit control }
MkDir(Edit1.Text);
if IOResult <> 0 then
MessageDlg('Cannot create directory', mtWarning, [mbOk], 0)
else
MessageDlg('New directory created', mtInformation, [mbOk], 0);
end;
See also
ChDir procedure, GetDir procedure, RmDir procedure
ModalResult property
Applies to
TBitBtn, TButton, TForm components
Declaration
property ModalResult: TModalResult;
Run-time only. The ModalResult property for forms is used to terminate a modal form.
By default, ModalResult is 0. Setting ModalResult to any nonzero value ends the form’s
modal state. When the user chooses to close a modal form, the button click sets
ModalResult to close the form. The value assigned to ModalResult becomes the return
value of the ShowModal function call which displayed the modal form.
Button controls have a ModalResult property also that is read only. Use a button’s
ModalResult property when you want a click of the button to close a modal form. For
example, if you create a dialog box with two buttons, OK and Cancel, set the
ModalResult property to mrOK for the OK button and mrCancel for the Cancel button.
When the user chooses either of these two buttons, the dialog box’s modal state ends
because ModalResult is greater than mrNone and the dialog box disappears. Using
ModalResult, you don’t have to write an event handler just to close the dialog box.
These constants are possible ModalResult values:
Constant Value
mrNone 0
mrOk idOK
mrCancel idCancel
mrAbort idAbort
mrRetry idRetry
mrIgnore idIgnore
Mode property
Applies to
TPen object; TMediaPlayer component
Example
The following code sets the mode of the pen of the Canvas of Form1 to the inverse of the
pen Color.
Form1.Canvas.Pen.Mode := pmNotCopy;
See also
Pen property, TPen object
Value Mode
mpNotReady Not ready
mpStopped Stopped
mpPlaying Playing
mpRecording Recording
mpSeeking Seeking
mpPaused Paused
mpOpen Open
Example
The following code declares an array of strings named ModeStr, indexed by the
TMPModes type. The Caption of a form is then set to the string describing the current
mode of the device:
const
Example
BatchMove1.Mode := batAppendUpdate;
Modified property
Applies to
TBitmap, TGraphic, TIcon, TMetafile objects, TDBEdit, TDBMemo, TEdit, TMaskEdit,
TMemo, TOLEContainer, TQuery, TStoredProc, TTable components
If the graphics object was modified, you can save the changes to a file with the
SaveToFile method. The next time the application is run, the object can be loaded from
the file with the LoadFromFile method.
Example
The following code saves the bitmap object in Graphic1 to a file if it was modified.
if Graphic1.Modified then Graphic1.SaveToFile('myfile.bmp');
Example
The following code saves the object in OLEContainer1 to the file OBJ.OLE if it was
modified.
if OLEContainer1.Modified then OLEContainer1.SaveToFile('OBL.OLE');
Example
procedure TForm1.Button1Click(Sender: TObject);
begin
if Edit1.Modified = True then
begin
MessageDlg('Edit box text was modified',
mtInformation, [mbOK], 0);
Declaration
property Monochrome: Boolean;
The Monochrome property determines if the bitmap displays in monochrome. If True, the
bitmap is monochrome. If False, the bitmap displays in color.
Example
The following code create Bitmap1 and sets its Monochrome property to True.
var
Bitmap1: TBitmap;
begin
Bitmap1 := TBitmap.Create;
Bitmap1.Monochrome := True;
end;
MouseToCell method
Applies to
TDrawGrid, TStringGrid components
Declaration
procedure MouseToCell(X, Y: Integer; var ACol, ARow: Longint);
The MouseToCell method returns the column and row of the cell the mouse pointer is
positioned on. The X and Y parameters are the screen coordinates of the mouse pointer.
The ACol parameter is the number of the column where the mouse pointer is positioned,
and the ARow parameter is the number of the row.
Usually the MouseToCell method is used in a mouse event handler, which supplies the
mouse coordinates to the method call.
Example
This example uses a string grid on a form. When the user selects a cell in the grid and
releases the mouse button, the column and row coordinates for the cell appear in the
cell. The code for displaying the coordinates is written in the OnMouseUp event handler:
procedure TForm1.FormCreate(Sender: TObject);
begin
StringGrid1.DefaultColWidth := 100;
end;
procedure TForm1.StringGrid1MouseUp(Sender: TObject; Button: TMouseButton;
Shift: TShiftState; X, Y: Integer);
var
Column, Row: Longint;
begin
StringGrid1.MouseToCell(X, Y, Column, Row);
StringGrid1.Cells[Column, Row] := 'Col ' + IntToStr(Column) +
',Row ' + IntToStr(Row);
end;
See also
CellRect method, OnMouseDown event, OnMouseMove event, OnMouseUp event
Move method
Applies to
TList, TStringList, TStrings objects
Declaration
procedure Move(CurIndex, NewIndex: Integer);
The Move method changes the position of an item in the list of a list object or in a list of
+
strings in a string object by giving the item a new index value. The CurIndex parameter is
the item’s current index, and the NewIndex parameter is the item’s new index value.
+
If a string in a string object has an associated object in the Objects property, Move moves +
both the string and the object.
+
Example
This example uses a list box and a button on a form. The list box contains items when
the form appears. When the user clicks the button, the fifth item in the list box is moved
+
to the top of the list box: +
procedure TForm1.FormCreate(Sender: TObject);
var
I: Integer;
+
begin
for I := 1 to 5 do
+
end;
ListBox1.Items.Add('Item ' + IntToStr(I));
+
procedure TForm1.Button1Click(Sender: TObject);
begin +
ListBox1.Items.Move(4, 0);
end; +
See also
Add method, Delete method, Exchange method, Objects property, Strings property
M
Move procedure System
Declaration
procedure Move(var Source, Dest; Count: Word);
The Move procedure copies Count bytes from a Source to Dest. No range-checking is
performed.
When the segment parts of Source and Dest are equal, Move compensates for overlaps
between the source and destination blocks. If the source and destination overlap but
their segment parts are not equal, Move will not compensate for overlaps and there is a
50% chance that Move will not work correctly. Borland Pascal’s static and dynamic
(heap) memory allocation schemes never create overlapping variables whose addresses
have different segment parts, so this problem can only occur if the addresses of Source
and Dest are modified or normalized by your program, or if they are provided by an
external source.
Whenever possible, use SizeOf to determine the count.
Example
var
A: array[1..4] of Char;
B: Longint;
begin
Move(A, B, SizeOf(A)); { SizeOf = safety! }
end;
See also
FillChar procedure, SizeOf function
MoveBy method
Applies to
TTable, TQuery, TStoredProc components
Declaration
procedure MoveBy(Distance: Integer);
The MoveBy method moves the dataset cursor by Distance records. If Distance is
negative, the move is backward. If Distance is positive, the movement is forward. If
Distance is zero, no move is done.
If the dataset is in Insert or Edit state, MoveBy will perform an implicit Post of any
pending data.
Example
{ Skip three records forward }
Table1.MoveBy(3);
See also
First method, Last method, Next method, Prior method
MovedCount property
Applies to
TBatchMove component
Declaration
property MovedCount: Longint;
Run-time and read only. MovedCount is the number of records which were actually
processed by the Execute method. This includes any records which had integrity or data
size problems.
Example
The following code draws a line from the upper-eft corner of a form to the point clicked
with the mouse:
procedure TForm1.FormMouseDown(Sender: TObject; Button: TMouseButton;
Shift: TShiftState; X, Y: Integer);
begin
Canvas.MoveTo(0, 0);
Canvas.LineTo(X, Y);
end;
See also
LineTo method
Declaration
procedure MoveTo(Destination: Longint; AttachMode: TAttachMode);
Description
The MoveTo method moves an outline item from one location to another within an
outline (TOutline component). The Destination parameter determines where to move the
item. Pass the Index value of another outline item in the Destination parameter. The
AttachMode parameter specifies how you want to attach the item to the destination
position. These are the possible values of AttachMode:
Value Meaning
oaAdd The item is attached as if added with the Add method. The moved item becomes the last
sibling of the item specified by the Destination parameter. The moved item will share the
same parent as the Destination item.
oaAddChild The item is attached as if added with the AddChild method. The moved item becomes the
last child of the item specified by the Destination parameter. The Destination item will
become the parent of the moved item.
oaInsert The item is attached as if inserted with the Insert method. The moved item replaces the
Destination item in the outline, while the Destination item and all other following items are
moved down one row.
Example
The following code moves the selected item to become the first item in the outline.
with Outline1.Items[Outline1.SelectedItem] do
MoveTo(0, oaInsert);
See also
ChangeLevelBy method
Name property
Applies to
All components; TFieldDef, TFieldDefs, TIndexDef, TIndexDefs, TFont, TParam, TParams
objects
For components
Declaration
property Name: TComponentName;
The Name property contains the name of the component as referenced by other
components. By default, Delphi assigns sequential names based on the type of the
component, such as ‘Button1’, ‘Button2’, and so on. You may change these to suit your
needs.
Example
The following code lists the names of all the components of Form1 in a list box.
var
I: Integer;
begin
for I := 0 to Form1.ComponentCount-1 do
ListBox1.Items.Add(Form1.Components[I].Name);
end;
Example
This code sets the font for all text that appears on the form to Times New Roman. If the
controls on the form have their ParentFont property set to True, text on these controls
will also be in Times New Roman.
procedure TForm1.FormCreate(Sender: TObject);
begin
Font.Name := 'Times New Roman';
end;
See also
ParentFont property
NetFileDir property
Applies to
TSession component
Declaration
property NetFileDir: string;
Run-time only. The NetFileDir property specifies the directory that contains the BDE
network control file, PDOXUSRS.NET. This property enables multiple users to share
Paradox tables on network drives. NetFileDir overrides the specification defined for the
Paradox driver in the BDE Configuration Utility.
All applications that need to share the same Paradox database must specify the same
directory, and all must have read/write/create rights for the directory.
See also
Session variable
Example
type
Str18 = string[18];
var
P: ^Str18;
begin
New(P);
P^ := 'Now you see it...';
Dispose(P); { Now you don't... }
end;
See also
Dispose procedure, FreeMem procedure, GetMem procedure
NewPage method
Applies to
TPrinter object
Declaration
procedure NewPage;
The NewPage method forces the current print job to begin printing on a new page in the
+
printer. It also increments the value of the PageNumber property and resets the value of
the Pen property of the Canvas back to (0, 0).
+
Example
+
This example uses a button on a form. When the user clicks the button, a rectangle is
printed twice, one per page.
+
To run this example successfully, you must add the Printers unit to the uses clause of
your unit.
+
procedure TForm1.Button1Click(Sender: TObject); +
+
begin
with Printer do
begin
BeginDoc;
Canvas.Rectangle(10, 10, 200, 200); +
NewPage;
Canvas.Rectangle(10, 10, 200, 200);
EndDoc;
+
end;
end;
+
See also
+
BeginDoc method, EndDoc method, Printer variable
+
NewStr function SysUtils N
Declaration
function NewStr(const S: string): PString;
The NewStr function allocates a copy of the string S on the heap and returns a pointer to
the newly allocated string. When your application finishes using the allocated string,
you should use DisposeStr to dispose of the string on the heap.
Do not change the length of strings allocated with NewStr. Increasing the length of the
string overwrites other variables on the heap. Decreasing the length of the string
prevents some of the memory from being deallocated.
Example
The following code allocates space for and places the string ‘New String’ in memory.
The pointer S points to the new string:
var
S: PString;
begin
S := NewStr('New String');
.
.
DisposeStr(S);
See also
DisposeStr procedure
Next method
Applies to
TForm, TMediaPlayer, TQuery, TStoredProc, TTable components
The Next method either activates the next form, media track, or record.
For forms
Declaration
procedure Next;
The Next method makes the next child form in the form sequence the active form.
For example, if you have three child forms within a parent form in your MDI
application and Form2 is the active form, the Next method makes Form3 the active form.
Calling Next again makes Form4 active. The next time your application calls Next, the
sequence starts over again and Form2 becomes the active form once again.
The Next method applies only to forms that are MDI parent forms (have a FormStyle
property value of fsMDIForm).
Example
The following code activates the next child of Form1.
Form1.Next;
See also
ArrangeIcons method, Cascade method, Previous method, Tile method
The Wait property determines whether control is returned to the application before the
+
Next method has completed. The Notify property determines whether Next generates an
OnNotify event.
+
Example
+
The following code opens a WAV audio file and fast-forwards to the end of the
medium.
+
MediaPlayer1.DeviceType := dtWAVAudio;
MediaPlayer1.FileName := ’c:\chimes.wav’;
+
MediaPlayer1.Open;
MediaPlayer1.Next;
+
See also +
Position property, Previous method, Tracks property
+
For tables, queries, and stored procedures +
Declaration +
procedure Next;
The Next method moves the cursor forward by one record. If the cursor is already on the
+
last record, it does not move. If the dataset is in Insert or Edit state, Next will perform an
implicit Post of any pending data. +
Example N
{ Move to the next record }
Table1.Next;
if Table1.Eof then { No more records };
See also
First method, Last method, MoveBy method, Prior method
NormalizeTopMosts method
Applies to
TApplication component
Declaration
procedure NormalizeTopMosts;
The NormalizeTopMosts method makes forms that have been designated as topmost
forms (their FormStyle is fsStayOnTop) behave as if they were not topmost forms. You’ll
find this method convenient to use if you want a message box or dialog box to appear
on top of a topmost form.
For example, while you do not have to call NormalizeTopMosts to use the Delphi
methods and functions that display message boxes (such as MessageBox and
MessageDlg), you should call it if you want to call Windows API functions directly to
display a message box. If you neglect to call NormalizeTopMosts, the message box won’t
display on top of the form, but the form remains on top. Any time you call Windows
API functions to display a window on top of a form, call NormalizeTopMosts first.
To return the forms designated as fsStayOnTop to be topmost again, call
RestoreTopMosts.
Example
The following code normalizes topmost forms before calling the MessageBox function in
the WinProcs unit. After the message box is closed, the topmost forms are restored.
begin
Application.NormalizeTopMosts;
MessageBox(Form1.Handle, 'This should be on top.', 'Message Box', MB_OK);
Application.RestoreTopMosts;
end;
See also
FormStyle property, RestoreTopMosts method
Notify property
Applies to
TMediaPlayer component
Declaration
property Notify: Boolean;
Run-time only. The Notify property determines whether the next call to a media control
method (Back, Close, Eject, Next, Open, Pause, PauseOnly, Play, Previous, StartRecording,
Resume, Rewind, Step, or Stop) generates an OnNotify event when the method has
completed.
If Notify is True, the next media control method generates OnNotify event upon
completion and stores the notification message in the NotifyValue property. If Notify is
False, the method does not generate an OnNotify event and NotifyValue remains
unchanged.
Notify affects only the next call to a media control method. After an OnNotify event,
Notify must be reset to affect any subsequent media control methods.
By default, Play and StartRecording function as if Notify is True. You must set Notify to
False before calling Play or StartRecording to prevent an OnNotify event from being
generated when playing or recording has finished. By default, all other media control
methods function as if Notify is False.
Set Notify to True if the next media control is expected to take a long time, so your
+
application is notified when the media control method has completed. If you set Notify
to True, you might want to set Wait to False so that control returns to the application
+
Note
before the media control method is finished.
If you try to resume a device that doesn’t support Resume, the device is resumed as if
+
you called the Play method. If you have assigned True to Notify before calling Resume (or
any other media control method), Notify doesn’t affect the call to Resume. Resume does
+
not generate an OnNotify event upon completion, and NotifyValue remains unchanged.
+
Example
The following code sets Notify to True after opening and playing the Microsoft Video for
+
the Windows file named DUCK.AVI. When the Play method is completed, an OnNotify
event occurs, which displays a message. +
procedure TForm1.BitBtn1Click(Sender: TObject);
begin
+
with MediaPlayer1 do begin
FileName := 'duck.avi'; +
+
Open;
Play;
Notify := True;
end;
end; +
procedure TForm1.MediaPlayer1Notify(Sender: TObject);
begin
if MediaPlayer1.NotifyValue=nvSuccessful then
+
end;
MessageDlg('Done playing video.', mtInformation, [mbOK], 0); N
NotifyValue property
Applies to
TMediaPlayer component
Declaration
property NotifyValue: TMPNotifyValues;
Run-time and read only. The NotifyValue property reports the result of the last media
control method (Back, Close, Eject, Next, Open, Pause, PauseOnly, Play, Previous,
StartRecording, Resume, Rewind, Step, or Stop) that requested a notification. Set Notify to
True before calling a media control method to request notification.
The following table lists the possible values for NotifyValue.
Value Result
nvSuccessful Command completed successfully
nvSuperseded Command was superseded by another command
Value Result
nvAborted Command was aborted by the user
nvFailure Command failed
Example
This example uses a media player component named MediaPlayer1. When the
application runs, the code attempts to play a CD in the CD audio device, and displays a
message dialog box indicating whether the attempt to play the CD was successful.
Before you can run this example, you must have a CD audio device installed correctly.
procedure TForm1.FormCreate(Sender: TObject);
begin
with MediaPlayer1 do
begin
DeviceType := dtCDAudio;
Open;
Play;
if NotifyValue <> nvSuccessful then
MessageDlg('Error playing CD audio', mtError, [mbOk], 0)
else
MessageDlg('Playing CD audio', mtInformation, [mbOk], 0);
Visible := False;
end;
end;
See also
OnNotify event
Example
This example uses a label and a button on a form. When the user clicks the button, the
current date and time appear as the caption of the label.
procedure TForm1.Button1Click(Sender: TObject);
begin
Label1.Caption := 'The date and time is ' + DateTimeToStr(Now);
end;
See also
Date function, DateTimeToStr function, Time function
If only one image is present, Delphi attempts to represent the other states by altering the
image slightly for the different states, although the stay down state is always the same as
the up state. If you aren’t satisfied with the results, you can provide additional images in
the bitmap.
Example
This example uses a speed button and a label on a form. When the example runs, the
number of images in the specified bitmap appears as the caption of the label.
See also
Glyph property
ObjClass property
Applies to
TOLEContainer component
Declaration
property ObjClass: string;
Specify the OLE class of an object in the ObjClass property. The class of an object is
typically the application name of the OLE server application without the .EXE
extension. See the documentation for the OLE server for specific information about its
OLE class.
At design time, specifying the ObjClass property displays the Insert Object dialog box
and initializes the OLE object. At run time, the ObjClass property is specified
automatically when you initialize the OLE object with the PInitInfo property.
Example
The following code tests to determine if “Paintbrush Picture” is the object class. If so, a
message is displayed in Label1 when Button1 is clicked.
procedure TForm1.Button1Click(Sender: TObject);
begin
if OLEContainer1.ObjClass = 'Paintbrush Picture' then
Label1.Caption := 'The object is a Paintbrush Picture';
end;
See also
ObjDoc property, ObjItem property
ObjDoc property
Applies to
TOLEContainer component
Declaration
property ObjDoc: string;
Specify the OLE document of an object in the ObjDoc property. The document of an
+
object is typically the name of the file containing the OLE information. See the OLE
server documentation for specific information about its OLE documents.
+
At design time, specifying the ObjDoc property displays the Insert Object dialog box and +
initializes the OLE object. At run time, the ObjDoc property is specified automatically
when you initialize the OLE object with the PInitInfo property, if the object is linked to
data in a file.
+
Example
+
The following code tests to determine if ‘c:\windows\256color.bmp’ is the object
document. If so, a message is displayed in Label1 when Button1 is clicked.
+
procedure TForm1.Button1Click(Sender: TObject);
begin
+
if OLEContainer1.ObjDoc = 'c:\windows\256color.bmp' then
Label1.Caption := 'The object document is c:\windows\256color.bmp';
+
end;
+
See also
ObjClass property, ObjItem property +
+
ObjectMenuItem property
+
Applies to
TForm component +
Declaration O
property ObjectMenuItem: TMenuItem;
ObjectMenuItem is used to specify the OLE object menu item. If you create a menu item
and specify it as the OLE object menu item with the ObjectMenuItem property, the item is
automatically enabled when an OLE object in an OLE container is selected.
The OLE object menu item can be used to activate or convert the selected object. All you
need to do is specify the menu item in the ObjectMenuItem component. The processing
of activating or converting the object is handled by the OLE server application.
Example
The following code assigns MyObject1 to the ObjectMenuItem property of Form1. When
an OLE container that contains an object is selected, the caption of the MyObject1 menu
item can be modified by the OLE server and the functionality of MyObject1 will be
handled by the server.
Form1.ObjectMenuItem := MyObject1;
Objects property
Applies to
TStringList, TStrings objects; TStringGrid component
Example
The following code allows the user to specify a bitmap file with the OpenDialog1 open
dialog box component when Form1 is created. Then, the bitmap file specified is added to
the Items list of ListBox1.
If ListBox1 is an owner-draw control (specified by a Style property of lbOwnerDrawFixed
or lbOwnerDrawVariable), the second procedure is the OnDrawItem event handler for
ListBox1. The bitmap in the Object property and the text of an item are retrieved and
displayed in Listbox1.
procedure TForm1.FormCreate(Sender: TObject);
var
TheBitmap: TBitmap;
begin
if OpenDialog1.Execute then
begin
TheBitmap := TBitmap.Create;
TheBitmap.LoadFromFile(OpenDialog1.FileName);
Example
The following code stores a TBitmap object called MyBitmap in row 3, column 10 of
StringGrid1.
StringGrid1.Objects[10, 3] := MyBitmap;
See also
Cells property, Cols property, Free method, Rows property
ObjItem property
Applies to
TOLEContainer component
Declaration
property ObjItem: string;
Specify the OLE item of an object in the ObjItem property. The item of an object is a
discrete unit of data within the OLE document containing the OLE information. See the
OLE server documentation for specific information about its OLE documents.
At design time, specifying the ObjItem property displays the Paste Special dialog box
and initializes the OLE object. At run time, the ObjItem property is specified
automatically when you initialize the OLE object with the PInitInfo property, if the
object linked is a more specific piece of data than is specified by the ObjDoc property.
Example
The following code tests to determine if “29 8 337 96” is the object item (this could be the
item if you copied a portion of a Paintbrush picture to the Clipboard and wanted to link
to the bitmap defined by the coordinates (29, 8) and (337, 96)). If so, a message is
displayed in Label1 when Button1 is clicked.
procedure TForm1.Button1Click(Sender: TObject);
begin
if OLEContainer1.ObjDoc = '29 8 337 96' then
Label1.Caption := 'The object item is 29 8 337 96';
end;
See also
ObjClass property
Example
begin
if Odd(5) then
Canvas.TextOut(10, 10, '5 is odd.')
else
Canvas.TextOut(10, 10, 'Something is odd!');
end;
Canvas.TextOut(5, Y, S);
Y := Y + Canvas.TextHeight(S) + 5;
S := 'The global data segment is $' + MakeHexWord(DSeg);
Canvas.TextOut(5, Y, S);
Y := Y + Canvas.TextHeight(S) + 5;
S := 'The stack segment is $' + MakeHexWord(SSeg);
Canvas.TextOut(5, Y, S);
Y := Y + Canvas.TextHeight(S) + 5;
S := 'The stack pointer is at $' + MakeHexWord(SPtr);
Canvas.TextOut(5, Y, S);
Y := Y + Canvas.TextHeight(S) + 5;
S := 'i is at offset $' + MakeHexWord(Ofs(i));
Canvas.TextOut(5, Y, S);
Y := Y + Canvas.TextHeight(S) + 5;
S := 'in segment $' + MakeHexWord(Seg(i));
Canvas.TextOut(5, Y, S);
end;
See also
Addr function, Seg function
OLEObjAllocated method
Applies to
TOLEContainer component
Declaration
function OleObjAllocated: Boolean;
The OLEObjAllocated method specifies whether an OLE container has been initialized
and therefore contains an OLE object. OLEObjAllocated returns True if an OLE object has
been allocated, or False if the OLE container is empty.
Example
The following code only initializes OLEContainer1 if it does not already contain an OLE
object, assuming TheInitInfo points to valid initialization information.
if not OLEContainer1.OLEObjAllocated then
OLEContainer1.PInitInfo := TheInitInfo;
See also
PInitInfo property
OnActivate event
Applies to
TApplication, TForm, TOLEContainer components
Declaration
property OnActivate: TNotifyEvent;
The OnActivate event for an OLE container occurs when the OLE object is activated as
specified by the AutoActivate property.
Example
The following code displays the number of times an OLE container has been activated in
Label1. The code assumes that TimesActivated is an Integer field of Form1 that is initialized
to 0 in the OnCreate event of Form1.
procedure TForm1.OleContainer1Activate(Sender: TObject);
begin
TimesActivated := TimesActivated + 1;
Form1.Label1.Caption := 'Times activated: '+IntToStr(TimesActivated);
end;
For an application
Declaration
property OnActivate: TNotifyEvent;
The OnActivate event for an application occurs when the application becomes active.
Your application becomes active when it is initially run or when focus is shifted from
another Windows application to your application.
Note Search Help for “Handling Application Events” for more information about creating
event handlers for application events.
Example
The following code is the entire unit which assigns the ApplicationActivate procedure to
the OnActivate event of the application. Note that ApplicationActivate is declared as a
method of Form1. The code that you add is notes with comments. The rest of the code is
generated by Delphi.
unit Unit1;
interface
uses
SysUtils, WinTypes, WinProcs, Messages, Classes, Graphics, Controls,
Forms, Dialogs;
type
TForm1 = class(TForm)
procedure ApplicationActivate(Sender: TObject); {Add this declaration line}
procedure FormCreate(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
var
Form1: TForm1;
Example
This example uses an edit box and a memo on a form. When the user switches the focus
between the two controls, the control that currently has the focus becomes red:
type
TForm1 = class(TForm)
Edit1: TEdit;
Memo1: TMemo;
Button1: TButton;
procedure FormCreate(Sender: TObject);
private
{ Private declarations }
public
procedure ColorControl(Sender: TObject);
end;
var
Form1: TForm1;
implementation
{$R *.DFM}
procedure TForm1.ColorControl(Sender: TObject);
begin
if Edit1.Focused then
Edit1.Color := clRed
else
Edit1.Color := clWindow;
if Memo1.Focused then
Memo1.Color := clRed
else
Memo1.Color := clWindow;
procedure TForm1.FormCreate(Sender: TObject);
begin
Screen.OnActiveControlChange := ColorControl;
end;
See also
ActiveControl property, ActiveForm property, OnActiveFormChange event
OnActiveFormChange event
Applies to
TScreen component
Declaration
property OnActiveFormChange: TNotifyEvent;
The OnActiveFormChange event occurs when a new form becomes the active form on the
screen (the form becomes the value of the ActiveForm property). Use the
OnActiveFormChange event to specify any special processing to occur just before a new
form becomes the active form.
Example
This example uses a two forms with a button on the first form. When the user clicks the
button, the second form appears. As the user switches between forms, the form that is
active is colored aqua:
type
TForm1 = class(TForm)
Button1: TButton;
procedure FormCreate(Sender: TObject);
procedure Button1Click(Sender: TObject);
private
{ Private declarations }
public
procedure ColorForm(Sender: TObject);
Declaration
property OnApply: TFDApplyEvent
The OnApply event occurs when the user clicks the Apply button in the Font dialog box.
The Apply button won’t appear in the Font dialog box unless the form has an OnApply
event handler. The user can use the Apply button to apply the font selected in the dialog
box to a component immediately before the dialog box is closed.
Example
This code displays the Font dialog box and puts an Apply button in it. When the user
clicks the Apply button, the font selected in the dialog box is applied to the Button1
button while the dialog box is still open.
procedure TForm1.Button1Click(Sender: TObject);
begin
FontDialog1.Execute;
end;
procedure TForm1.FontDialog1Apply(Sender: TObject; Wnd: Word);
begin
Button1.Font := FontDialog1.Font;
end;
See also
Execute method, Font property
OnCalcFields event
Applies to
TTable, TQuery, TStoredProc components
Declaration
property OnCalcFields: TDataSetNotifyEvent;
The OnCalcFields event is used to set the values of calculated fields. OnCalcFields is called
when a dataset reads a record from the database. In addition, if the dataset’s
AutoCalcFields property is True, OnCalcFields is called when a non-calculated field is
modified while the dataset is in Edit or Insert state.
Typically, the OnCalcFields event will be called often, so it should be kept short.
OnCalcFields should not perform any actions that modify the dataset (or the linked
dataset if it is part of a master-detail relationship), because this can lead to recursion.
While the OnCalcFields event is executed, a dataset will be put in CalcFields state. When a
dataset is in CalcFields state, you cannot set the values of any fields other than calculated
fields. After OnCalcFields is completed, the dataset will return to its previous state.
The first call to the OnCalcFields event handler may occur before all components in your
application have been initialized. If your handler requires access to another component,
use the Edit|Creation Order command to ensure that the components are created in the
correct order.
OnChange event
Applies to
TBitmap, TBrush, TCanvas, TFont, TGraphic, TGraphicsObject, TMetafile, TPen, TPicture,
TStringList objects; TComboBox, TDBComboBox, TDBEdit, TDBLookupCombo, TDBMemo,
TDBRadioGroup, TDDEClientItem, TDDEServerItem, TDirectoryListBox, TDriveComboBox,
TEdit, TFileListBox, TFilterComboBox, TMaskEdit, TMemo, TQuery, TScrollBar, TTable,
TTabSet, TBCDField, TBlobField, TBooleanField, TBytesField, TCurrencyField, TDateField,
TDateTimeField, TFloatField, TGraphicField, TIntegerField, TMemoField, TSmallintField,
TStringField, TTimeField, TVarBytesField, TWordField components
Example
The following code updates the contents of an edit box with the linked text from a DDE
server when the data is updated.
procedure TForm1.DdeClientItem1Change(Sender: TObject);
begin
Edit1.Text := DDEClientItem1.Text;
end;
Example
The following code displays a message if the data accessed by DBMemo1 changes.
procedure TForm1.DBMemo1Change(Sender: TObject);
begin
MessageDlg('Data has changed',mtInformation,[mbOK],0);
end;
For fields
Declaration
property OnChange: TFieldNotifyEvent;
OnChange is activated when the contents of the field are modified. If a data-aware
control is linked to the field, OnChange is not activated until the control attempts to store
the changes into the current record.
You can take any special actions required by the event by assigning a method to this
property.
Example
Field1.OnChange := CapitalizeFirstLetter;
For combo boxes, the OnChange event also occurs when an item is selected in the drop
+
down list. +
For string list objects, the OnChange event occurs when a change to a string stored in the
list of strings changes. +
Example +
This example uses a color grid on a form. The color grid is a component on the Samples
page of the Component palette. When the user clicks a color rectangle or drags the
mouse cursor across the color grid, the color of the form changes.
+
procedure TForm1.ColorGrid1Change(Sender: TObject); +
+
begin
Color := ColorGrid1.ForegroundColor;
end;
See also
+
OnChanging event
+
OnChanging event +
Applies to
+
TCanvas object
+
Declaration
property OnChanging: TNotifyEvent;
+
An OnChanging event occurs immediately before the graphic contained in the canvas is
modified.
O
OnClick event
Applies to
TBitBtn, TButton, TCheckBox, TComboBox, TDBCheckBox, TDBComboBox, TDBEdit,
TDBImage, TDBListBox, TDBLookupCombo, TDBLookupList, TDBMemo, TDBNavigator,
TDBRadioGroup, TDBText, TDirectoryListBox, TDrawGrid, TDriveComboBox, TFileListBox,
TFilterComboBox, TForm, TGroupBox, TImage, TLabel, TListBox, TMaskEdit, TMediaPlayer,
TMemo, TMenuItem, TNotebook, TOutline, TPaintBox, TPanel, TRadioButton, TScrollBar,
TScrollBox, TSpeedButton, TStringGrid, TTabSet components
An OnClick event occurs when the user presses and releases the mouse button when the
mouse pointer is over one of the control buttons of the media player control, or when
the user presses Spacebar when the media player control has focus. When the media
player control has focus, the user can select which control button to click when the
Spacebar is pressed with the Left Arrow or Right Arrow keys.
Example
This example uses a label and a media player on a form. When the user clicks one of the
media player buttons, the caption of the label indicates which button was clicked. For
this example to run successfully, you must have a CD audio device installed correctly.
procedure TForm1.FormCreate(Sender: TObject);
begin
MediaPlayer1.DeviceType := dtCDAudio;
MediaPlayer1.Open;
MediaPlayer1.Left := 20;
MediaPlayer1.Top := 12;
Label1.Top := 44;
Label1.Left := 20;
Label1.Color := clYellow;
Label1.Font.Name := 'Arial';
Label1.Caption := 'Click Me';
end;
procedure TForm1.MediaPlayer1Click(Sender: TObject; Button: TMPBtnType;
var DoDefault: Boolean);
begin
case Button of
btPlay :
begin
Label1.Caption := 'Playing';
Label1.Left := 20;
end;
btPause:
begin
Label1.Caption := 'Paused';
Label1.Left := 48;
end;
btStop:
begin
Label1.Caption := 'Stopped';
Label1.Left := 76;
end;
btNext:
begin
Label1.Caption := 'Next';
Label1.Left := 104;
end;
btPrev:
begin
Label1.Caption := 'Previous';
Label1.Left := 132;
Example
The form in this example changes color each time the user clicks it:
procedure TForm1.FormClick(Sender: TObject);
begin
Randomize;
Color := Random(65535);
end;
See also
Click method, OnDblClick event
OnClose event
Applies to
TDDEClientConv, TForm components
See also
OnCloseQuery event, OnOpen event
Example
The following code displays a message when a conversation is closed.
OnCloseQuery event
Applies to
TForm component
Declaration
property OnCloseQuery: TCloseQueryEvent;
The OnCloseQuery event occurs when an action to close the form takes place (when the
Close method is called or when the user chooses Close from the form’s System menu).
An OnCloseQuery event handler contains a Boolean CanClose variable that determines
whether a form is allowed to close. It’s default value is True. See the TCloseQueryEvent
type for more information about CanClose.
You can use an OnCloseQuery event handler to ask users if they are sure they really want
the form closed immediately. For example, you can use the handler to display a message
box that prompts the user to save a file before closing the form.
Example
When the user attempts to close the form in this example, a message dialog appears that
asks the user if it is OK to close the form. If the user chooses the OK button, the form
closes. If the user chooses Cancel, the form doesn’t close.
procedure TForm1.FormCloseQuery(Sender: TObject; var CanClose: Boolean);
begin
if MessageDlg('Close the form?', mtConfirmation,
[mbOk, mbCancel], 0) = mrCancel then
CanClose := False;
end;
See also
Close method, OnClose event
OnColEnter event
Applies to
TDBGrid component
Declaration
property OnColEnter: TNotifyEvent;
The OnColEnter event occurs when the user clicks a cell in a column or moves to a
+
column with the Tab key within the data grid. Use the OnColEnter event to specify any
processing you want to occur as soon as a column is entered.
+
Example
+
The following code concatenates an asterisk to the display label of a field when the
column is entered.
+
procedure TForm1.DBGrid1ColEnter(Sender: TObject);
begin
+
with DBGrid1.SelectedField do
DisplayLabel := '* ' + DisplayLabel;
+
end;
+
See also
OnColExit event +
OnColExit event
+
+
Applies to
TDBGrid component +
Declaration +
property OnColExit: TNotifyEvent;
The OnColExit event occurs when the user uses the Tab key to move out of a column or
+
clicks a cell in another column. Use the OnColExit event to specify any special processing
you want to occur when exiting the column. O
Example
The following code deletes the first two characters from the display label of the selected
field when exiting a column. Note that FirstTime is a Boolean field that prevents
characters from being deleted the first time a column is exited. Use this code in
conjunction with code in the example of OnColEnter to modify the appearance of the
display label of columns while they are entered.
procedure TForm1.DBGrid1ColExit(Sender: TObject);
var
TheLabel: string;
begin
if FirstTime then
FirstTime := False
else
begin
with DBGrid1.SelectedField do
begin
TheLabel := DisplayLabel;
Delete(TheLabel, 1, 2);
DisplayLabel := TheLabel;
end;
end;
end;
See also
OnColExit event
OnCollapse event
Applies to
TOutline component
Declaration
property OnCollapse: EOutlineChange;
An OnCollapse event occurs when an expanded outline item that has subitems is
collapsed. An expanded outline item is collapsed when the user double-clicks it at run
time, when the FullCollapse method is called, or when its Expanded property is set to
False. When collapsed, the subitems no longer appear in the outline and the plus picture
or closed picture for the parent item is displayed if the appropriate OutlineStyle has been
selected.
Example
The following code displays the text from a collapsed outline item in a message dialog
box.
procedure TForm1.Outline1Collapse(Sender: TObject; Index: Longint);
var
TheStr: string;
begin
TheStr := Outline1.Items[Index].Text;
MessageDlg(TheStr+' has collapsed.', mtInformation, [mbOK],0);
end;
See also
OnExpand event, PictureClosed property, PicturePlus property
OnColumnMoved event
Applies to
TDrawGrid, TStringGrid components
Declaration
property OnColumnMoved: TMovedEvent;
The OnColumnMoved event occurs when the user moves a column using the mouse. The
+
user can move a column only if the Options property set includes the value goColMoving. +
Example
The following code permits one column to be moved (assuming [goColMoving] is
+
specified for the Options property at design time), then locks the columns by preventing
any more moves.
+
procedure TForm1.StringGrid1ColumnMoved(Sender: TObject; FromIndex, ToIndex: Longint);
begin
+
StringGrid1.Options := StringGrid1.Options - [goColMoving];
end;
+
See also +
OnRowMoved event
+
OnCreate event +
Applies to +
TForm component
+
Declaration
property OnCreate: TNotifyEvent;
+
The OnCreate event specifies which event handler to call when the form is first created.
You can write code in the event handler that sets initial values for properties and does
+
any processing you want to occur before the user begins interacting with the form.
Delphi creates a form when the application is run by calling the Create method.
O
Note When writing code in an OnCreate event handler, don’t fully qualify a component
reference by including the name of the form in the reference. For example, if the form is
named Form1 and contains an Edit1 edit box control, don’t refer to the edit box control
with the Form1.Edit1 name. Because Form1 doesn’t yet exist when this code executes,
your application would crash if you used the fully qualified name. Instead, simply use
the name Edit1.
When a form is being created and its Visible property is True, the following events occur
in the order listed:
• OnActivate
• OnShow
• OnCreate
• OnPaint
Example
This very simple OnCreate event handler assures that the form is the same color as the
Windows system color of your application workspace:
See also
OnActivate event, OnDestroy event, OnPaint event
OnDataChange event
Applies to
TDataSource component
Declaration
property OnDataChange: TDataChangeEvent;
The OnDataChange occurs when the State property changes from dsInactive, or when a
data-aware control notifies the TDataSource that something has changed.
Notification occurs when the following items change because of field modification or
scrolling to a new record: field component, record, dataset component, content, and
layout. The Field parameter to the method may be nil if more than one of the fields
changed simultaneously (as in a move to a different record). Otherwise, Field is the field
which changed.
See also
OnStateChange event, State property
OnDblClick event
Applies to
TComboBox, TDBComboBox, TDBEdit, TDBGrid, TDBImage, TDBListBox,
TDBLookupCombo, TDBLookupList, TDBMemo, TDBNavigator, TDBText,
TDirectoryListBox, TDrawGrid, TDriveComboBox, TEdit, TFileListBox, TFilterComboBox,
TForm, TGroupBox, TImage, TLabel, TListBox, TMaskEdit, TMemo, TNotebook,
TOLEContainer, TOutline, TPaintBox, TPanel, TRadioButton, TScrollBox, TSpeedButton,
TStringGrid components
Example
The following code minimizes an application when it’s deactivated. Note that
AppDeactivate should be declared a method of TForm1.
procedure TForm1.FormCreate(Sender: TObject);
begin
Application.OnDeactivate := AppDeactivate;
end;
procedure TForm1.AppDeactivate(Sender: TObject);
begin
Application.Minimize;
end;
See also
OnActivate event
OnDestroy event
Applies to
TForm component
Declaration
property OnDestroy: TNotifyEvent;
The OnDestroy event occurs when a form is about to be destroyed. A form is destroyed
by the Destroy, Free, or Release methods, or when the main form of the application is
closed.
Example
The following code explicitly allocates memory for a a pointer in the OnCreate event of
Form1, then releases the memory in the OnDestroy event. Assume that MyPtr is a Pointer
type field of TForm1.
procedure TForm1.FormCreate(Sender: TObject);
begin
New(MyPtr);
end;
procedure TForm1.FormDestroy(Sender: TObject);
begin
Dispose(MyPtr);
end;
See also
OnCreate event
OnDragDrop event
Applies to
TBitBtn, TButton, TCheckBox, TComboBox, TDBCheckBox, TDBComboBox, TDBEdit,
TDBGrid, TDBImage, TDBListBox, TDBLookupCombo, TDBLookupList, TDBMemo,
TDBNavigator, TDBText, TDBRadioGroup, TDirectoryListBox, TDrawGrid,
TDriveComboBox, TEdit, TFileListBox, TFilterComboBox, TForm, TGroupBox, TImage,
TListBox, TMaskEdit, TMemo, TNotebook, TOLEContainer, TOutline, TPaintBox, TPanel,
TRadioButton, TScrollBar, TScrollBox, TShape, TStringGrid, TTabSet components
Declaration
property OnDragDrop: TDragDropEvent;
The OnDragDrop event occurs when the user drops an object being dragged. Use the
OnDragDrop event handler to specify what you want to happen when the user drops an
object. The Source parameter of the OnDragDrop event is the object being dropped, and
the Sender is the control the object is being dropped on. The X and Y parameters are the
coordinates of the mouse positioned over the control.
See also +
DragCursor property, DragMode property, OnDragOver event, OnEndDrag event
+
OnDragOver event +
Applies to +
TBitBtn, TButton, TCheckBox, TComboBox, TDBCheckBox, TDBComboBox, TDBEdit,
TDBGrid, TDBImage, TDBListBox, TDBLookupCombo, TDBLookupList, TDBMemo,
TDBNavigator, TDBText, TDBRadioGroup, TDirectoryListBox, TDrawGrid,
+
TDriveComboBox, TEdit, TFileListBox, TFilterComboBox, TForm, TGroupBox, TImage,
TListBox, TMaskEdit, TMemo, TNotebook, TOLEContainer, TOutline, TPaintBox, TPanel,
+
TRadioButton, TScrollBar, TScrollBox, TShape, TStringGrid, TTabSet components
O
Declaration
property OnDragOver: TDragOverEvent;
The OnDragOver event occurs when the user drags an object over a component. Usually
you’ll use an OnDragOver event to accept an object so the user can drop it.
The OnDragOver event accepts an object when its Accept parameter is True.
Usually, you will want the cursor to change shape, indicating that the control can accept
the dragged object if the user drops it. You can change the shape of the cursor by
changing the value of the DragCursor property for the control at either design or run
time before an OnDragOver event occurs.
Example
This OnDragOver event handler permits the list box to accept a dropped label:
procedure TForm1.ListBox1DragOver(Sender, Source: TObject; X, Y: Integer;
State: TDragState; var Accept: Boolean);
begin
Accept := Source is TLabel;
end;
The Source parameter identifies what is being dragged. The Sender is the control being
dragged over.
This code permits the list box to accept any dropped control:
procedure TForm1.ListBox1DragOver(Sender, Source: TObject; X, Y: Integer;
State: TDragState; var Accept: Boolean);
begin
Accept := True;
end;
See also
DragMode property, OnDragDrop event, OnEndDrag event, TDragState type
OnDrawCell event
Applies to
TDrawGrid, TStringGrid components
Declaration
property OnDrawCell: TDrawCellEvent;
The OnDrawCell event occurs whenever the contents of a grid cell need to be
redisplayed. For example, it occurs when the user selects a cell or scrolls the grid. How a
cell is redrawn depends on the value of the DefaultDrawing property.
If DefaultDrawing is False, you must write the code that handles all drawing within the
cell in the OnDrawCell event handler.
Example
The following code draws a focus rectangle around each of the cells of StringGrid1.
procedure TForm1.StringGrid1DrawCell(Sender: TObject; Col, Row: Longint;
Rect: TRect; State: TGridDrawState);
begin
StringGrid1.Canvas.DrawFocusRect(Rect);
end;
OnDrawDataCell event
Applies to
TDBGrid component
Declaration
property OnDrawDataCell: TDrawDataCellEvent;
The OnDrawDataCell event occurs whenever the contents of a data grid cell need to be
+
redisplayed. For example, it occurs when the user selects a cell or scrolls the grid. How a
cell is redrawn depends on the value of the DefaultDrawing property.
+
If DefaultDrawing is False, you must write the code that handles all the drawing within +
the cell in the OnDrawDataCell event handler.
+
Example
The following code fills the cells of DBGrid1 with the pattern defined by the Brush of the
Canvas of DBGrid1.
+
procedure TForm1.DBGrid1.DrawDataCell(Sender: TObject; Rect: TRect; Field: TField; +
+
State: TGridDrawState)
begin
DBGrid1.Canvas.FillRect(Rect);
end;
+
OnDrawItem event +
Applies to +
TComboBox, TDBComboBox, TDBListBox, TListBox, TOutline components
+
Declaration
property OnDrawItem: TDrawItemEvent;
+
The OnDrawItem event occurs whenever an item in an owner-draw outline, list box, or
combo box needs to be redisplayed. For example, it occurs when the user selects an item
+
or scrolls the outline, list box, or combo box. OnDrawItem events occur only for outlines
with the Style value osOwnerDraw, list boxes with the Style values lbOwnerDrawFixed or
O
lbOwnerDrawVariable, and for combo boxes with the Style values csOwnerDrawFixed or
csOwnerDrawVariable.
OnDrawItem passes four parameters to its handler describing the item to be drawn:
• a reference to the control containing the item
• the index of the item in that control
• a rectangle in which to draw
• the state of the item (selected, focused, and so on)
The size of the rectangle that contains the item is determined either by the ItemHeight
property for fixed owner-draw controls or by the response to the OnMeasureItem event
for variable owner-draw controls.
Example
Here is a typical handler for an OnDrawItem event. In the example, a list box with the
lbOwnerDrawFixed style draws a bitmap to the left of each string.
procedure TForm1.ListBox1DrawItem(Control: TWinControl; Index: Integer; Rect: TRect;
State: TOwnerDrawState);
var
Bitmap: TBitmap; { temporary variable for the item’s bitmap }
Offset: Integer; { text offset width }
begin
with (Control as TListBox).Canvas do { draw on the control canvas, not on the form }
begin
FillRect(Rect); { clear the rectangle }
Offset := 2; { provide default offset }
Bitmap := TBitmap(Items.Objects[Index]); { get the bitmap for this item }
if Bitmap <> nil then
begin
BrushCopy(Bounds(Rect.Left + 2, Rect.Top, Bitmap.Width, Bitmap.Height), Bitmap,
Bounds(0, 0, Bitmap.Width, Bitmap.Height), clRed); { render the bitmap }
Offset := Bitmap.width + 6; { add four pixels between bitmap and text }
end;
TextOut(Rect.Left + Offset, Rect.Top, Items[Index]) { display the text }
end;
end;
Note that the Rect parameter automatically provides the proper location of the item
within the control’s canvas.
See also
ItemHeight property, OnMeasureItem event
OnDrawTab event
Applies to
TTabSet component
Declaration
property OnDrawTab: TDrawTabEvent;
The OnDrawTab event occurs when a tab needs to redisplay only for tab set controls that
have the Style property value of tsOwnerDraw. For example, it happens when the user
selects a tab or scrolls the tabs using an owner-draw tab set control.
You must write the code in the OnDrawTab event handler to draw the tab.
OnDrawTab occurs just after the OnMeasureTab event, which contains the code to
calculate the width of the tab needed. The height of the tab is determined by the value of
the TabHeight property of the tab set control. The code you write in the OnDrawTab
event handler, therefore, must use the width determined with the OnMeasureTab event
to draw the tab.
Example
The following code loads a bitmap from the Objects property of the Tabs list of the
DriveTabSet tab set component. This bitmap is then drawn on the tab, along with the text
from the Tabs list.
OnEndDrag event
Applies to
TBitBtn, TButton, TCheckBox, TComboBox, TDBCheckBox, TDBComboBox, TDBEdit,
TDBGrid, TDBImage, TDBListBox, TDBLookupCombo, TDBMemo, TDBNavigator,
TDBText, TDBRadioGroup, TDirectoryListBox, TDrawGrid, TDriveComboBox, TEdit,
TFileListBox, TFilterComboBox, TGroupBox, TImage, TListBox, TMaskEdit, TMemo,
TNotebook, TOLEContainer, TOutline, TPanel, TRadioButton, TScrollBar, TScrollBox,
TShape, TStringGrid, TTabSet components
Declaration
property OnEndDrag: TEndDragEvent;
The OnEndDrag event occurs whenever the dragging of an object ends, either by
dropping the object or by canceling the dragging. Use the OnEndDrag event handler to
specify any special processing you want to occur when dragging stops. If the dragged
object was dropped and accepted by the control, the Target parameter of the OnEndDrag
event is True. If the object was not dropped successfully, the value of Target is nil.
Example
This code displays a message in a label named Status. The message displayed depends
on whether or not the dragged label control was dropped into and accepted by a list box
control successfully:
procedure TForm1.LabelEndDrag(Sender, Target: TObject; X, Y: Integer);
var
S: string;
begin
S := (Sender as TLabel).Name + ' was dropped... and ';
if Target <> nil then S := S + 'accepted!'
else S := S + 'rejected!';
Status.Caption := S;
end;
The Target parameter is the list box and Sender is the label.
See also
EndDrag method, OnDragDrop event
OnEnter event
Applies to
All windowed controls
Declaration
property OnEnter: TNotifyEvent;
The OnEnter event occurs when a component becomes active. Use the OnEnter event
handler to specify any special processing you want to occur when a component
becomes active.
Note The OnEnter event does not occur when switching between forms or between another
Windows application and your application.
Note The OnEnter event for a TPanel or THeader component never occurs as panels and
headers never receive focus.
See also
ActiveControl property, OnActivate event, OnExit event +
OnException event
+
Applies to
O
TApplication component
Declaration
property OnException: TExceptionEvent;
The OnException event occurs when an unhandled exception occurs in your application.
By default, the HandleException method calls the OnException event handler, which calls
ShowException to display a message dialog box appears indicating an error occurred.
You can change this behavior by specifying what processing you want to occur in the
OnException event handler.
Note Search Help for “Handling Application Events” for more information about creating
event handlers for application events.
Example
The following code defines the default exception handling of the application, assuming
AppException is declared a method of TForm1.
procedure TForm1.FormCreate(Sender: TObject);
begin
Application.OnException := AppException;
end;
procedure TForm1.AppException(Sender: TObject; E: Exception);
begin
Application.ShowException
end;
OnExecuteMacro event
Applies to
TDDEServerConv component
Declaration
property OnExecuteMacro : TMacroEvent;
The OnExecuteMacro event occurs when a DDE client application sends a macro to a
DDE server conversation component. Write code to process the macro in the
OnExecuteMacro event handler. See the DDE client application documentation for
information about how it sends macros. If the DDE client is a Delphi application, a
macro is sent with the ExecuteMacro method of the TDDEClientConv component.
Example
The following code clears the contents of a memo in the server application if the
appropriate message is sent from the client application.
procedure TForm1.DdeServerConv1ExecuteMacro(Sender: TObject; Msg: TStrings);
begin
if Msg.Strings[0] = 'Edit|Clear' then
Memo1.Clear;
end;
OnExit event
Applies to
All windowed controls
Declaration
property OnExit: TNotifyEvent;
The OnExit event occurs when the input focus shifts away from one control to another.
Use the OnExit event handler when you want special processing to occur when this
control ceases to be active.
Note The OnExit event does not occur when switching between forms or between another
Windows application and your application.
Note The OnExit event for a TPanel or THeader component never occurs as panels and headers
never receive focus.
Declaration
property OnExpand: EOutlineChange;
An OnExpand event occurs when a collapsed outline item having subitems is expanded.
A collapsed outline item is expanded when the user double-clicks on it at run time,
when its Expanded property is set to True, or when the FullExpand method of the
TOutlineNode object is called. When expanded, the subitems appear in the outline and
the minus picture or open picture for the parent item is displayed if the appropriate
OutlineStyle has been selected.
Example
The following code displays the text from a collapsed outline item in a message dialog
box.
procedure TForm1.Outline1Expand(Sender: TObject; Index: Longint);
var
TheStr: string;
begin
TheStr := Outline1.Items[Index].Text;
MessageDlg(TheStr+' has expanded.', mtInformation, [mbOK],0);
end;
See also
OnCollapse event, PictureMinus property, PictureOpen property
OnFind event
Applies to
TFindDialog, TReplaceDialog components
Declaration
property OnFind: TNotifyEvent;
The OnFind event occurs whenever the user chooses the Find Next button in the Find or
Replace dialog box. Use the OnFind event to specify what you want to happen when the
user chooses the Find Next button.
Example
The following text compares the FindText to the Text of the Items of Outline1. If the string
is found, a message is displayed and I-1 specifies the index of the matching item.
procedure TForm1.FindDialog1Find(Sender: TObject);
var
I: Integer;
Found: Boolean;
begin
I := 1;
Found := False;
repeat
if Outline1.Items[I].Text = FindDialog1.FindText then
begin
MessageDlg('Found!', mtInformation, [mbOK], 0);
Found := True;
end;
I := I+1;
until (I > Outline1.ItemCount) or (Found);
end;
See also
OnReplace event
OnGetEditText event
Applies to
TDrawGrid, TStringGrid components
Declaration
property OnGetEditText: TGetEditEvent;
The OnGetEditText event occurs when the Options property set contains the value
goEditing and the grid needs to redisplay the text of a cell in the grid. For example, the
grid needs to redisplay the text when the user scrolls the grid or the user changes the
data.
You write the code to retrieve the text of the cell in the OnGetEditText event handler.
When the user edits data in a grid, the OnSetEditText event occurs to change the actual
data, then the OnGetEditText event occurs to display the changed data in the grid.
Example
The following code appends ‘My ‘ to any text entered in StringGrid1.
procedure TForm1.StringGrid1GetEditText(Sender: TObject; ACol,
ARow: Longint; var Value: OpenString);
begin
Value := 'My ' + Value;
end;
See also
OnGetEditMask event, OnSetEditText event
OnGetText event
Applies to
TBCDField, TBlobField, TBooleanField, TBytesField, TCurrencyField, TDateField,
TDateTimeField, TFloatField, TGraphicField, TIntegerField, TMemoField, TSmallintField,
TStringField, TTimeField, TVarBytesField, TWordField components
Declaration
property OnGetText: TFieldGetTextEvent;
The OnGetText event is activated when the DisplayText or Text properties are referenced.
The DisplayText parameter indicates if the event should supply the text in display
format or in edit format for the Text property. If OnGetText has been assigned a method,
the default processing for DisplayText or Text does not occur; the event handler is
expected to perform any conversion required to display the value.
By assigning a method to this property, you can take any special actions required by the
event.
Example
Field1.OnGetText := MyFormatMethod;
OnHide event
Applies to
TForm component
Declaration
property OnHide: TNotifyEvent;
The OnHide event occurs just before the form is hidden on the screen. Use the OnHide
event to specify any special processing you want to happen just before the form
disappears.
A form that is an MDI child form (FormStyle is fsMDIChild) loses its window handle
+
when it is hidden. If your application performs some operation that causes the window
handle to come back, such as adding items to a list box on the form, an exception is
+
raised. +
Example
This example uses two forms, each with a label and a button. When the user clicks a
+
button, the other form appears and the current form disappears. Also, a message
appears in the label of the form that is showing, indicating that the other form is hidden. +
This is the implementation section of Unit1:
implementation
+
{$R *.DFM} +
uses Unit2;
procedure TForm1.Button1Click(Sender: TObject);
+
begin
Form2.Show; +
+
Hide;
end;
procedure TForm1.FormHide(Sender: TObject);
begin
Form2.Label1.Caption := 'Form1 is hiding';
+
end;
end.
+
This is the implementation section of Unit2: +
implementation
{$R *.DFM}
O
uses Unit1;
procedure TForm2.Button1Click(Sender: TObject);
begin
Form1.Show;
Hide;
end;
procedure TForm2.FormHide(Sender: TObject);
begin
Form1.Label1.Caption := 'Form2 is hiding';
end;
end.
See also
OnShow event
OnHelp event
Applies to
TApplication component
Declaration
property OnHelp: THelpEvent;
The OnHelp event occurs when your application receives a request for help. Use the
OnHelp event handler to specify any special processing you want to occur when help is
requested.
The HelpContext and the HelpJump methods automatically trigger the OnHelp event.
Note Search Help for “Handling Application Events” for more information about creating
event handlers for application events.
Example
The following code changes the Help file for the application to the results of the Open
dialog component. AppHelp should be assigned to the OnHelp event handler of
Application in the OnCreate event of Form1.
function TForm1.AppHelp(Command: Word; Data: Longint): Boolean;
begin
if OpenDialog1.Execute then
Application.HelpFile := OpenDialog1.FileName;
end;
See also
HelpCommand method, HelpContext property, HelpFile property, THelpEvent type
OnHint event
Applies to
TApplication component
Declaration
property OnHint: TNotifyEvent;
The OnHint event occurs when the user positions the mouse pointer over a control with
a Hint property value other than an empty string (‘’). Use the OnHint event handler to
perform any special processing you want to happen when the OnHint event occurs.
A common use of the OnHint event is to display the value of a control or menu item’s
Hint property as the caption of a panel control (TPanel), thereby using the panel as a
status bar. Using the Hint property, you can specify a Help Hint and a usually longer
hint that appears elsewhere when the OnHint event occurs.
Search Help for “Handling Application Events” for more information about creating
+
event handlers for application events. +
Example
This example uses a panel component, a menu, and an edit box on a form. You can
+
design the menu as you want, but remember to include a value for the Hint property for
each menu item in the menu. Also, specify a value for the Hint property of the edit box.
+
Align the panel at the bottom of the form (choose alBottom as the value of the Align
property), and left justify the caption of the panel (choose taLeftJustify as the value of the +
Alignment property).
The OnHint event is an event of the TApplication component. You can’t use the Object
+
Inspector to generate an empty event handler for TApplication, so you will need to write
your own OnHint event handler. To accomplish this, you create a method of the TForm1 +
object and give it an appropriate name, such as DisplayHint. You write the method in the
implementation part of the unit, but you must also remember to declare the method in +
the TForm1 type declaration in the public section.
In the DisplayHint method, you assign the Hint property of the application to the Caption +
property of the panel component.
One task remains. The OnHint event is an event of TApplication, so you must assign the
+
new method you created as the method used by the OnHint event. You can do this in
the form’s OnCreate event handler.
+
This code shows the complete type declaration, the new method, and the OnCreate event
handler. When the user runs the application and positions the cursor over the edit box
+
or a menu item on the menu, the specified hint appears as the caption of the panel at the
bottom of the form:
+
type
TForm1 = class(TForm)
O
Button1: TButton;
Panel1: TPanel;
Edit1: TEdit;
procedure FormCreate(Sender: TObject);
private
{ Private declarations }
public
procedure DisplayHint(Sender: TObject);
end;
var
Form1: TForm1;
implementation
{$R *.FRM}
procedure TForm1.DisplayHint(Sender: TObject);
begin
Panel1.Caption := Application.Hint;
end;
See also
OnCreate event
OnIdle event
Applies to
TApplication component
Declaration
property OnIdle: TIdleEvent
The OnIdle event occurs whenever the application is idle. Use the OnIdle event handler
to specify any special processing to occur when your application is idle. Your
application is idle when it is processing code, for example, or when it is waiting for
input from the user.
The TIdleEvent type has a Boolean parameter Done that is True by default. When Done is
True, the Windows API WaitMessage function is called when OnIdle returns. WaitMessage
yields control to other applications until a new message appears in the message queue
of your application. If Done is False, WaitMessage is not called.
Note Search Help for “Handling Application Events” for more information about creating
event handlers for application events.
Example
The following code allows other applications to be processed while Application is idle.
AppIdle should be declared as a method of TForm1.
procedure TForm1.FormCreate(Sender: TObject);
begin
Application.OnIdle := AppIdle;
end;
end;
MessageDlg('Alt+F10 pressed down', mtInformation, [mbOK], 0);
O
See also
KeyPreview property, OnKeyPress event, OnKeyUp event
OnKeyPress event
Applies to
TBitBtn, TButton, TCheckBox, TComboBox, TDBCheckBox, TDBComboBox, TDBEdit,
TDBGrid, TDBImage, TDBListBox, TDBLookupCombo, TDBMemo, TDirectoryListBox,
TDrawGrid, TDriveComboBox, TEdit, TFileListBox, TFilterComboBox, TForm, TListBox,
TMaskEdit, TMemo, TOLEContainer, TOutline, TRadioButton, TScrollBar, TStringGrid
components
Declaration
property OnKeyPress: TKeyPressEvent;
The OnKeyPress event occurs when a user presses a single character key. Use the
OnKeyPress event handler when you want something to happen as a result of pressing a
single key.
The Key parameter in the OnKeyPress event handler is of type Char; therefore, the
OnKeyPress event registers the ASCII character of the key pressed. Keys that don’t
correspond to an ASCII Char value (Shift or F1, for example) don’t generate an
OnKeyPress event. Key combinations (such as Shift+A), generate only one OnKeyPress
event (for this example, Shift+A results in a Key value of “A” if Caps Lock is off). If you
want to respond to non-ASCII keys or key combinations, use the OnKeyDown or
OnKeyUp event handlers.
Example
This event handler displays a message dialog box specifying which key was pressed:
procedure TForm1.FormKeyPress(Sender: TObject; var Key: Char);
begin
MessageDlg(Key + ' has been pressed', mtInformation, [mbOK], 0)
end;
See also
KeyPreview property
OnKeyUp event
Applies to
TBitBtn, TButton, TCheckBox, TComboBox, TDBCheckBox, TDBComboBox, TDBEdit,
TDBGrid, TDBImage, TDBListBox, TDBLookupCombo, TDBMemo, TDirectoryListBox,
TDrawGrid, TDriveComboBox, TEdit, TFileListBox, TFilterComboBox, TForm, TListBox,
TMaskEdit, TMemo, TOLEContainer, TOutline, TRadioButton, TScrollBar, TStringGrid
components
Declaration
property OnKeyUp: TKeyEvent;
The OnKeyUp event occurs when the user releases a key that has been pressed. Use the
OnKeyUp event handler when you want special processing to occur when a key is
released. The OnKeyUp handler can respond to all keyboard keys including function
keys and keys combined with the Shift, Alt, and Ctrl keys and pressed mouse buttons. The
Key parameter of the OnKeyUp event handler is of type Word; therefore, you must use
virtual key codes to determine the key pressed. You can find a table of virtual key codes
in the Help system; search for the topic Virtual Key Codes.
Example
The following code changes a form’s color to aqua when a key is pressed. When the key
is released, the form’s color reverts to the original color. Note that the KeyPreview
property of the form must be set to True to capture all key presses, even if a control has
focus:
OnMeasureItem event
Applies to
TComboBox, TDBComboBox, TDBListBox, TListBox components
Declaration
property OnMeasureItem: TMeasureItemEvent;
The OnMeasureItem event occurs whenever an application needs to redisplay an item in
an owner-draw list box or combo box with a variable style. That is, for a list box, the
Style property is lbOwnerDrawVariable, or for a combo box, the Style property is
csOwnerDrawVariable.
The OnMeasureItem event passes three parameters to its handler describing the item to
measure:
• The control containing the item
• The index of the item in the control
• The height of the item
The OnMeasureItem event handler should specify the height in pixels that the given item
will occupy in the control. The Height parameter is a var parameter, which initially
contains the default height of the item or the height of the item text in the control’s font.
The handler can set Height to a value appropriate to the contents of the item, such as the
height of a graphical image to be displayed within the item.
After the OnMeasureItem event occurs, the OnDrawItem event occurs, rendering the item
with the measured size.
Example
Here is a typical handler for an OnMeasureItem event. The example assumes that a
variable owner-draw list box already has bitmaps associated with each of its strings. It
sets the height of the item to the height of the associated bitmap if that height is greater
than the default height.
procedure TForm1.ListBox1MeasureItem(Control: TWinControl; Index: Integer;
var Height: Integer);
var
Bitmap: TBitmap;
begin
with Control as TListBox do
begin
Bitmap := TBitmap(Items.Objects[Index]);
if Bitmap <> nil then
if Bitmap.Height > Height then Height := Bitmap.Height;
end;
end;
OnMeasureTab event
Applies to
TTabSet component
Declaration
property OnMeasureTab: TMeasureTabEvent;
The OnMeasureTab event occurs when the Style property of the tab set control is
+
tsOwnerDraw and an application needs to redisplay a tab in a tab set control. In the
OnMeasureTab event handler, you write the code to calculate the width needed to draw
+
the tab. After the OnMeasureTab event occurs, the OnDrawTab event occurs. You write
the code to draw the tab using the width calculated in OnMeasureTab in the OnDrawTab
+
event handler.
The Index parameter of the TMeasureTabEvent method pointer is the position of the tab in
+
the tab set control. The TabWidth parameter is the width of the tab. +
Example
The following code measures the width of a bitmap stored in the Objects property of the
+
Tabs list of the DriveTabSet tab set component. It then makes the width of the tab two
pixels wider than the bitmap width. +
procedure TFMForm.DriveTabSetMeasureTab(Sender: TObject; Index: Integer;
var TabWidth: Integer);
+
var
BitmapWidth: Integer; +
begin
BitmapWidth := TBitmap(DriveTabSet.Tabs.Objects[Index]).Width;
Inc(TabWidth, 2 + BitmapWidth);
+
end;
+
OnMessage event +
Applies to
+
TApplication component
O
Declaration
property OnMessage: TMessageEvent;
The OnMessage event occurs when your application receives a Windows message. By
creating an OnMessage event handler in your application, you can call other handlers
that respond to the message. If your application doesn’t have a specific handler for an
incoming message, the message is dispatched and Windows handles the message. An
OnMessage event handler lets your application trap a Windows message before
Windows itself processes it.
Note Search Help for “Handling Application Events” for more information about creating
event handlers for application events.
Example
The following code displays the time of the most recently received Windows message in
the Caption of Label1. AppMessage should be declared a method of TForm1.
procedure TForm1.FormCreate(Sender: TObject);
begin
Application.OnMessage := AppMessage;
end;
See also
ProcessMessages method
OnMinimize event
Applies to
TApplication component
Declaration
property OnMinimize: TNotifyEvent;
The OnMinimize event occurs when the application is minimized, either because the
user minimizes the main window, or because of a call to the Minimize method. Use the
OnMinimize event handler to put code that performs any special processing you want to
happen when the application is minimized.
See also
OnRestore event, Restore method
OnMouseDown event
Applies to
TBitBtn, TButton, TCheckBox, TDBCheckBox, TDBEdit, TDBImage, TDBListBox,
TDBLookupCombo, TDBMemo, TDBNavigator, TDBText, TDirectoryListBox, TDrawGrid,
TEdit, TFileListBox, TForm, TGroupBox, TImage, TLabel, TListBox, TMaskEdit, TMemo,
TNotebook, TOLEContainer, TOutline, TPaintBox, TPanel, TRadioButton, TScrollBox,
TShape, TSpeedButton, TStringGrid, TTabSet components
Declaration
property OnMouseDown: TMouseEvent;
The OnMouseDown event occurs when the user presses a mouse button with the mouse
pointer over a control. Use the OnMouseDown event handler when you want some
processing to occur as a result of pressing a mouse button.
The Button parameter of the OnMouseDown event identifies which mouse button was
pressed. By using the Shift parameter of the OnMouseDown event handler, you can
respond to the state of the mouse buttons and shift keys. Shift keys are the Shift, Ctrl, and
Alt keys.
Declaration
property OnMouseMove: TMouseMoveEvent;
The OnMouseMove occurs when the user moves the mouse pointer when the mouse
pointer is over a control. Use the OnMouseMove event handler when you want
something to happen when the mouse pointer moves within the control.
By using the Shift parameter of the OnMouseDown event handler, you can respond to the
state of the mouse buttons and shift keys. Shift keys are the Shift, Ctrl, and Alt keys.
Example
The following code updates two labels when the mouse pointer is moved. The code
assumes you have two labels on the form, lblHorz and lblVert. If you attach this code to
the OnMouseMove event of a form, lblHorz continually displays the horizontal position
of the mouse pointer, and lblVert continually displays the vertical position of the mouse
pointer while the pointer is over the form.
See also
OnMouseDown event, OnMouseUp event
OnMouseUp event
Applies to
TBitBtn, TButton, TCheckBox, TDBCheckBox, TDBEdit, TDBImage, TDBListBox,
TDBLookupCombo, TDBMemo, TDBNavigator, TDBText, TDirectoryListBox, TDrawGrid,
TEdit, TFileListBox, TForm, TGroupBox, TImage, TLabel, TListBox, TMaskEdit, TMemo,
TNotebook, TOLEContainer, TOutline, TPaintBox, TPanel, TRadioButton, TScrollBox,
TShape, TSpeedButton, TStringGrid, TTabSet components
Declaration
property OnMouseUp: TMouseEvent;
The OnMouseUp event occurs when the user releases a mouse button that was pressed
with the mouse pointer over a component. Use the OnMouseUp event handler when you
want processing to occur when the user releases a mouse button.
The OnMouseUp event handler can respond to left, right, or center mouse button presses
and shift key plus mouse button combinations. Shift keys are the Shift, Ctrl, and Alt keys.
Example
The following code draws a rectangle when the user presses a mouse button, moves the
mouse, and releases the mouse button. When the mouse button is released, the rectangle
appears on the form’s canvas. Its top-left and bottom-right corners are defined by the
location of the mouse pointer when the user pressed and released the mouse button.
var
StartX, StartY: Integer; {Declare in interface section of form’s unit}
{Use this code as the OnMouseDown event handler of the form:}
procedure TForm1.FormMouseDown(Sender: TObject; Button: TMouseButton;
Shift: TShiftState; X, Y: Integer);
begin
StartX := X;
StartY := Y;
end;
{Use this code as the OnMouseUp event handler of the form:}
procedure TForm1.FormMouseUp(Sender: TObject; Button: TMouseButton;
Shift: TShiftState; X, Y: Integer);
begin
Form1.Canvas.Rectangle(StartX, StartY, X, Y);
Example
Attach the following code to the OnNotify event handler of a media player named
MediaPlayer1. If the Notify property of MediaPlayer1 is set to True, this code displays the
value of the NotifyValue property in a message dialog box.
procedure TForm1.MediaPlayer1Notify(Sender: TObject);
var
MyString: string;
begin
case MediaPlayer1.NotifyValue of
nvSuccessful : MyString := 'Success!';
See also
NotifyValue property, Wait property
OnOpen event
Applies to
TDDEClientConv, TDDEServerConv components
Declaration
property OnOpen: TNotifyEvent;
An OnOpen event occurs when a DDE conversation is opened. A DDE conversation can
be initiated automatically or manually. Automatically open a conversation by setting
the value of the ConnectMode property to ddeAutomatic. When the form containing the
DDE client conversation component is created at run time, the DDE conversation opens.
Manually open a conversation by setting the value of ConnectMode to ddeManual and
calling the OpenLink method.
Example
The following code sends a macro to the server and closes the link immediately after
opening it.
procedure TForm1.DdeClientConv1Open(Sender: TObject);
begin
with DDEClientConv1 do
begin
ExecuteMacro('File|New', False);
CloseLink;
end;
end;
See also
OnClose event
OnPageChanged event
Applies to
TNotebook component
OnPaint event
Applies to
TForm, TPaintBox component
Declaration
property OnPaint: TNotifyEvent;
The OnPaint event occurs when Windows requires the form or paint box to paint, such
as when the form or paint box receives focus or becomes visible when it wasn’t
previously. Your application can use this event to draw on the canvas of the form or
paint box.
Example
The following code is an entire unit that loads a background bitmap onto the Canvas of
the main form in the OnPaint event handler.
unit Unit1;
interface
uses
SysUtils, WinTypes, WinProcs, Messages, Classes, Graphics, Controls, Forms, Dialogs;
type
TForm1 = class(TForm)
procedure FormPaint(Sender: TObject);
procedure FormCreate(Sender: TObject);
private
TheGraphic: TBitmap; { Add this declaration for the graphic}
public
{ Public declarations }
end;
var
Form1: TForm1;
implementation
{$R *.DFM}
procedure TForm1.FormPaint(Sender: TObject); { OnPaint event handler}
begin
Form1.Canvas.Draw(0, 0, TheGraphic); { Draw the graphic on the Canvas }
end;
procedure TForm1.FormCreate(Sender: TObject); { OnCreate event handler }
begin
TheGraphic := TBitmap.Create; { Create the bitmap object }
TheGraphic.LoadFromFile('C:\APP\BKGRND.BMP'); { Load the bitmap from a file}
end;
end.
See also
Canvas property
OnPassword event
Applies to
TSession component
Declaration
property OnPassword: TPasswordEvent;
Run-time only. The OnPassword event is activated whenever a Paradox table is opened
+
and the Borland Database Engine reports that the application does not have sufficient
access rights. The value of Sender is the Session component. Continue determines whether
+
the caller will make another attempt to access the database. The procedure should add
any available additional passwords and set Continue to True. If there are no additional
+
passwords available, set Continue to False.
If no OnPassword event is defined, Session will create a default dialog box for the user to
+
enter a new password. +
OnPokeData event +
Applies to
+
TDDEServerItem component
+
Declaration
property OnPokeData: TNotifyEvent
+
The OnPokeData event occurs when the DDE client application pokes data to your DDE +
server application. When a client pokes data, it sends text to the linked DDE server. The
Text and Lines properties will be updated to contain the poked data, then the
OnPokeData event occurs.
+
If the DDE client is a Delphi application that uses a TDDEClientConv component, data is +
poked when the PokeData or PokeDataLines method is called.
+
Example
The following code uses a Boolean variable FInPoke to protect poked data from being
lost by a DDE server application. DoOnPoke is the OnPokeData event handler for the
O
DDE server item component named DDETestItem. When data is poked, FInPoke is set to
True, the poked data is stored in the Lines property of Memo2, and FInPoke is set back to
False.
The data should be protected because the server data is updated when the Lines of
Memo1 are updated by the user. DoOnChange, the OnChange event handler for Memo1,
tests FInPoke before updating the server data in DDETestItem. Otherwise, data poked
from the client could be lost when Memo1.Lines is changed.
var
FInPoke: Boolean;
.
.
.
procedure TDdeSrvrForm.doOnPoke(Sender: TObject);
begin
FInPoke := True;
Memo2.Lines := DdeTestItem.Lines;
FInPoke := False;
end;
See also
OnExecuteMacro event
OnPopup event
Applies to
TPopupMenu component
Declaration
property OnPopup: TNotifyEvent;
The OnPopup event occurs whenever a pop-up menu appears either because the user
right-clicks the component when the pop-up menu’s AutoPopup is True or because the
Popup method executed. Use the OnPopup event handler when you want some special
processing to occur when the component’s pop-up menu appears.
Example
The following code enables the Paste item from the pop-up menu if the Clipboard has
text data.
procedure TForm1.PopupMenu1Popup(Sender: TObject);
begin
Paste1.Enabled := Clipboard.HasFormat(CF_TEXT);
end;
See also
PopupMenu property
OnPostClick event
Applies to
TMediaPlayer component
Declaration
property OnPostClick: EMPPostNotify;
An OnPostClick event is generated after the code of the OnClick event handler has been
called. If Wait is True when the media player was clicked, OnPostClick won’t be called
until the completion of the OnClick code. If Wait is False, control can return to the
application before completion of the OnClick code; therefore, the OnPostClick event may
+
occur before the actions initiated by the OnClick event have completed. +
For example, if the user clicks the Play button and the DoDefault parameter of the
OnClick event handler for the media player is True, the media is played. If the media is +
long enough, it will still be playing when the OnPostClick event is generated if Wait is
True. If Wait is False, however, OnPostClick won’t occur until the media has finished
playing.
+
See also
+
OnClick event +
OnReplace event +
Applies to
+
TReplaceDialog components
+
Declaration +
+
property OnReplace: TNotifyEvent;
The OnReplace event occurs whenever the user chooses either the Replace or the Replace
All button in the Replace dialog box. Use the OnReplace event to specify the processing
that replaces text. +
Because the OnReplace event occurs when the user chooses either the Replace or Replace
All button, the code you write in the OnReplace event handler should determine which +
button was chosen and supply the appropriate logic. Use the frReplace and frReplaceAll
values in the Options set to determine which button was chosen. O
Example
The following code calls the user-defined routine DoReplace if the Replace button was
clicked, or calls the user-defined routine DoReplaceAll if the ReplaceAll button was
clicked.
procedure TForm1.ReplaceDialog1Replace(Sender: TObject);
begin
if (ReplaceDialog1.Options*[frReplace])=[frReplace] then DoReplace
else if (ReplaceDialog1.Options*[frReplaceAll])=[frReplaceAll] then DoReplaceAll;
end;
See also
OnFind event
OnResize event
Applies to
TDBNavigator, TForm, TPanel, TScrollBox components
Declaration
property OnResize: TNotifyEvent;
The OnResize event occurs whenever the form is resized while an application is running.
Use the OnResize event handler when you want something to happen in your
application when the form is resized.
Example
The following code keeps the right edge on Button1 against the right edge of Form1
when Form1 is resized.
procedure TForm1.FormResize(Sender: TObject);
begin
Button1.Left := (Form1.Width)-Button1.Width;
end;
OnRestore event
Applies to
TApplication component
Declaration
property OnRestore: TNotifyEvent;
The OnRestore event occurs when the previously minimized application is restored to its
normal size, either because the user restores the application, or because the application
calls the Restore method. Use the OnRestore event handler to put code that performs any
special processing you want to happen as the application is restored.
See also
Minimize method, OnMinimize event
OnRowMoved event
Applies to
TDrawGrid, TStringGrid components
Declaration
property OnRowMoved: TMovedEvent;
The OnRowMoved event occurs when the user moves a row using the mouse. The user
can move a row only if the Options property set includes the value goRowMoving.
Example
The following code displays the number of rows a row was moved in a label.
10. This shows how you can use the OnScroll event handler to move the thumb tab by
different increments than specified by the LargeChange and SmallChange properties. +
procedure TForm1.ScrollBar1Scroll(Sender: TObject; ScrollCode: TScrollCode;
var ScrollPos: Integer); O
begin
if ScrollCode = scPageUp then ScrollPos := ScrollPos - 1
else if ScrollCode = scPageDown then ScrollPos := ScrollPos + 10;
Label1.Caption := IntToStr(ScrollPos);
end;
OnSelectCell event
Applies to
TDrawGrid, TStringGrid component
Declaration
property OnSelectCell: TSelectCellEvent;
The OnSelectCell event occurs when the user selects a cell in a draw grid or string grid.
Use the OnSelectCell event handler to write the code that handles the selecting of a cell.
Using the CanSelect parameter of the event handler type, your code can determine
whether the user can select a cell or not.
Example
The following code determines that the user cannot select a cell containing the text ‘No’.
procedure TForm1.StringGrid1SelectCell(Sender: TObject; Col, Row: Longint;
var CanSelect: Boolean);
begin
CanSelect := not (StringGrid1.Cells[Col,Row]='No')
end;
OnSetEditText event
Applies to
TDrawGrid, TStringGrid component
Declaration
property OnSetEditText: TSetEditTextEvent;
The OnSetEditText event occurs when the user edits the text in the grid. The user can edit
the text only if the Options property set contains the value goEditing. The OnSetEditText
event makes the actual changes to the data. Use the OnSetEditText event handler to write
the code to handle the changes to the text within a cell of the grid.
When the user edits data in a grid, the OnSetEditText event occurs to change the actual
data, then the OnGetEditText event occurs to display the changed data in the grid.
See also
OnGetEditText event
OnSetText event
Applies to
TBCDField, TBlobField, TBooleanField, TBytesField, TCurrencyField, TDateField,
TDateTimeField, TFloatField, TGraphicField, TIntegerField, TMemoField, TSmallintField,
TStringField, TTimeField, TVarBytesField, TWordField components
Declaration
property OnSetText: TFieldSetTextEvent;
The OnSetText event is activated when the Text property is assigned a value. If
OnSetText has been assigned a method, the default processing for Text does not occur.
The event handler must store the text provided by Text.
By assigning a method to this property, you can take any special actions required by the
event.
Example
This example uses three speed buttons on a panel. The code changes the color, width,
and position of the text in the Help Hint for the third speed button.
You must declare the DoShow method in the type declaration of the form. Once it is
declared, write the code for the DoShow method in the implementation part of the unit.
Finally, in the OnCreate event handler for the form, assign the method to the
OnShowHint event of the application.
type
TForm1 = class(TForm)
Panel1: TPanel;
SpeedButton1: TSpeedButton;
SpeedButton2: TSpeedButton;
SpeedButton3: TSpeedButton;
procedure FormCreate(Sender: TObject);
private
{ Private declarations }
public
procedure DoShowHint(var HintStr: string; var CanShow: Boolean;
var HintInfo: THintInfo;
end;
var
Form1: TForm1;
implementation
{$R *.DFM}
procedure TForm1.DoShowHint(var HintStr: string; var CanShow: Boolean;
var HintInfo: THintInfo);
begin
if HintInfo.HintControl = SpeedButton3 then
begin
with HintInfo do
begin
HintColor := clAqua; { Changes only for this hint }
MaxHintWidth := 120; {Hint text word wraps if width is greater than 120 }
Inc(HintPos.X, SpeedButton3.Width); { Move hint to right edge }
end;
end;
end;
procedure TForm1.FormCreate(Sender: TObject);
begin
Application.OnShowHint := DoShowHint;
end;
end.
See also
Hint property, OnHint event, ParentShowHint property, ShowHint property
OnSized event
Applies to
THeader component
Declaration
property OnSized: TSectionEvent;
See also
AllowResize property, OnSized event
OnStateChange event
Applies to
TDataSource component
Declaration
property OnStateChange: TNotifyEvent;
OnStateChange is activated when the State property changes.
By assigning a method to this property, you can react programmatically to state
changes. For example, this event is useful for enabling or disabling buttons (for
example, enabling an edit button only when a table is in edit mode), or displaying
processing messages.
Note OnChangeState can occur even for nil datasets, so it is important to protect any reference
to the DataSet property with a nil test:
if DataSource1.Dataset <> nil then
ƒ
See also
OnDataChange event
OnStatusLineEvent event
Applies to
TOLEContainer component
Declaration
property OnStatusLineEvent: TStatusLineEvent;
An OnStatusLineEvent event occurs if an OLE server application has a message to
display in the status line of the OLE container application when an OLE object is
activated in place. Typically, your OLE container application handles an
OnStatusLineEvent event by displaying the message string in its own status bar.
Example
The following code displays the status line message from the OLE server in Panel1.
procedure TForm1.OleContainer1StatusLineEvent(Sender: TObject; Msg: string);
begin
Panel1.Caption := Msg;
end;
OnTimer event
Applies to
TTimer component
Declaration
property OnTimer: TNotifyEvent;
The OnTimer event is used to execute code at regular intervals. Place the code you want
+
to execute within the OnTimer event handler. +
The Interval property of a timer component determines how frequently the OnTimer
event occurs. Each time the specified interval passes, the OnTimer event occurs. +
Example +
Here is an example of an OnTimer event handler that moves a ball slowly across the
screen: +
procedure TForm1.Timer1Timer(Sender: TObject);
begin +
+
Timer1.Interval := 100;
Shape1.Left := Shape1.Left + 1;
end;
See also
+
Interval property
+
OnTopLeftChanged event +
Applies to
+
TDrawGrid, TStringGrid components
+
Declaration
property OnTopLeftChanged: TNotifyEvent;
+
The OnTopLeftChanged event occurs whenever the value of either the TopRow property
or LeftCol property changes.
O
Example
The following code displays the latest top row and left column of StringGrid1.
procedure TForm1.StringGrid1TopLeftChanged(Sender: TObject);
begin
with StringGrid1 do
MessageDlg('The top row is now '+IntToStr(TopRow)+
' and the left col is now '+IntToStr(LeftCol), mtInformation, [mbOK],0);
end;
OnUpdateData event
Applies to
TDataSource component
Declaration
property OnUpdateData: TNotifyEvent;
OnUpdateData is activated by the Post or UpdateRecord method of a dataset component
when the current record is about to be updated in the database. It causes all data-aware
controls connected to the data source to be notified of the pending update, allowing
them to change their associated fields to the current values in the controls. By assigning
a method to this property, you can react programmatically to updates.
See also
BeforePost event
OnValidate event
Applies to
TBCDField, TBlobField, TBooleanField, TBytesField, TCurrencyField, TDateField,
TDateTimeField, TFloatField, TGraphicField, TIntegerField, TMemoField, TSmallintField,
TStringField, TTimeField, TVarBytesField, TWordField components
Declaration
property OnValidate: TFieldNotifyEvent;
The OnValidate event is activated when a field is modified. If a data-aware control is
linked to the field, changes in the control do not activate OnValidate until the control
attempts to store the results of those changes into the current record.
By assigning a method to this property, you can perform any special validation required
for the field.
Example
Field1.OnValidate := ValidateFieldRange;
Open method
Applies to
TClipboard object; TDatabase, TMediaPlayer, TQuery, TStoredProc, TTable components
Clipboard, your application doesn’t have to call Open. If you want to add a series of
+
items to the Clipboard, however, Open prevents the contents from being overwritten
with each addition.
+
When your application has added all items to the Clipboard, it should call the Close +
method.
+
Example
The following code opens a Clipboard object before two items (text from an edit box and
an OLE object from an OLE container) are copied to the Clipboard. Then the Clipboard
+
is closed. +
Clipboard.Open;
Edit1.CopyToClipboard;
OLEContainer1.CopyToClipboard;
+
Clipboard.Close;
+
See also
Clear method, Clipboard variable, Close method
+
For media player controls
+
+
Declaration
procedure Open; +
The Open method opens a multimedia device. The multimedia device type must be
specified in the DeviceType property before you can open a device.
+
Upon completion, Open stores a numerical error code in the Error property, and the
corresponding error message in the ErrorMessage property.
O
The Wait property determines whether control is returned to the application before the
Open method is completed. The Notify property determines whether Open generates an
OnNotify event.
Example
This example begins playing an audio CD when the application begins running. When
the application is closed, the CD automatically stops playing. For this example to run
successfully, you must have an audio CD device installed correctly.
procedure TForm1.FormCreate(Sender: TObject);
begin
with MediaPlayer1 do
begin
DeviceType := dtCDAudio;
Visible := False;
Open;
Play;
end;
end;
See also
AutoOpen property, Close method
Example
try
Table1.Open;
except
on EDataBaseError do { The dataset could not be opened };
end;
See also
Close method
For databases
Declaration
procedure Open;
The Open method connects the TDatabase component to the server (or BDE for Paradox
and dBASE databases). This is the same as setting Connected to True.
Example
Database1.Open;
OpenCurrent method
Applies to
TDirectoryListBox component
Example
Database := Session.OpenDatabase(‘DBDEMOS’);
try
begin
{Do Something}
finally
Session.CloseDatabase(‘DBDEMOS’);
end;
See also
Session variable
OpenLink method
Applies to
TDDEClientConv component
Declaration
function OpenLink: Boolean;
The OpenLink method initiates a new DDE conversation. If the conversation was
successfully opened, an OnOpen event occurs and OpenLink returns True. If the
conversation wasn’t successfully opened, OpenLink returns False.
Example
The following code requests data if a link is open.
if OpenLink then DDEClientConv1.RequestData(DDEClientItem1.DDEItem);
See also
CloseLink method
Options property
Applies to
TIndexDef object; TColorDialog, TDBGrid, TDBLookupCombo, TDBLookupList, TDrawGrid,
TFindDialog, TFontDialog, TOpenDialog, TOutline, TPrintDialog, TReplaceDialog,
TSaveDialog, TStringGrid components
The Options property is a set of options that affects how dialog boxes, outlines, and grids
appear and behave. The possible values contained within the set vary depending on the
type of dialog box or if the component is an outline or grid control.
Value Meaning
cdFullOpen Displays the custom coloring options when the Color dialog opens
cdPreventFullOpen Disables the Create Custom Colors button in the Color dialog box so the user cannot
create their own custom colors.
cdShowHelp Adds a Help button to the Color dialog box.
The default value is [ ], the empty set, meaning all of these values are False and none of
+
the options are in effect. +
Example
This example displays the Color dialog box with a Help button and the Create Custom
+
Colors button dimmed. The form is colored whatever color the user chooses. +
+
procedure TForm1.Button1Click(Sender: TObject);
begin
ColorDialog1.Options := [cdPreventFullOpen, cdShowHelp];
if ColorDialog1.Execute then
Color := ColorDialog1.Color; +
end;
+
See also
Color property, CustomColors property +
For Font dialog boxes +
Declaration
+
property Options: TFontDialogOptions; +
These are the possible values that can be included in the Options set for the Fonts dialog
box: +
Value Meaning +
fdAnsiOnly If True, the user can select fonts that use the Windows character set only; that is, the
user can’t choose a font that contains only symbols because they aren’t displayed in
the Font combo box.
O
fdEffects If True, the Effects check boxes and the Color list box appear in the Font dialog box.
The user uses the Effects check boxes to specify strikeout or underlined text and the
Color list box to select a color for the selected font. If fdEffects is False, the Effects check
boxes and Color list box don’t appear in the Font dialog box.
fdFixedPitchOnly If True, only monospaced fonts are displayed in the Font combo box.
fdForceFontExist If True and the user enters a font name in the Font combo box and chooses OK, a
message dialog box appears informing the user the font name is invalid.
fdLimitSize If True, the MinFontSize and MaxFontSize properties can limit the number of fonts
available in the dialog box.
fdNoFaceSel If True, when the dialog box appears, no font name is selected in the Font combo box.
fdNoOEMFonts If True, only fonts that aren’t vector fonts are displayed in the Font combo box.
fdScalableOnly If True, only fonts that can be scaled are displayed in the Font combo box.
fdNoSimulations If True, only fonts that aren’t GDI font simulations are displayed in the Font combo
box.
fdNoSizeSel If True, when the dialog box appears, no size is selected in the Size combo box.
fdNoStyleSel If True, when the dialog box appears, no style is selected in the Style combo box.
fdNoVectorFonts Same as fdNoOEMFonts.
fdShowHelp If True, a Help button appears in the dialog box.
Value Meaning
fdTrueTypeOnly If True, only TrueType fonts are displayed in the Font list box.
fdWysiwyg If True, only fonts that are available to both the printer and the screen appear in the
Font combo box.
The default value is [fdEffects], meaning that only the fdEffects option is in effect.
Example
This example sets the options of the Font dialog box so that when the dialog box
displays, only TrueType fonts show in the list of fonts and no font size is selected:
procedure TForm1.Button1Click(Sender: TObject);
begin
FontDialog1.Options := [fdTrueTypeOnly, fdNoSizeSel];
if FontDialog1.Execute then
Memo1.Font := FontDialog1.Font;
end;
See also
Font property
Declaration
property Options: TPrintDialogOptions;
These are the possible values that can be included in the Options set for the Print dialog
box:
Value Meaning
poHelp If True, a Help button appears in the dialog box.
poPageNums If True, the Pages radio button is enabled and the user can specify a range of pages
to print.
poPrintToFile If True, a Print to File check box appears in the dialog box, giving the user the option
to print to a file rather than to a printer.
poSelection If True, the Selection radio button is enabled and the user can choose to print
selected text.
poWarning If True and if no printer is installed, a warning message appears when the user
chooses OK.
poDisablePrintToFile If True and poPrintToFile is True, the Print to File check box is dimmed when the
dialog box appears. If poPrintToFile is False, setting poDisablePrintToFile to True has
no effect because the dialog box won’t have a Print to File check box.
The default value is [ ], the empty set, meaning that none of the possible options are in
effect.
end;
...
+
See also +
PrintRange property, PrintToFile property
+
For Open and Save dialog boxes +
Declaration +
+
property Options: TOpenOptions;
These are the possible values that can be included in the Options set for the Open and
Save dialog boxes:
+
Value
ofAllowMultiSelect
Meaning
When True, this option allows users to select more than one file in the File Name
list box.
+
ofCreatePrompt When True, this option displays a dialog box with a message if the user enters a
file name that doesn’t exist in the File Name edit box and chooses OK. The
+
ofExtensionDifferent
message tells the user the file doesn’t exist and asks if the user wants to create a
new file with that name.
This option is set when the file name returned from the dialog box has an
O
extension that differs from the default file extension, the value in the DefaultExt
property. Your application can then use this information. Setting an
ofExtensionDifferent value with the Object Inspector has no meaning.
ofFileMustExist If True, this option displays a dialog box with a message if the user enters a file
that doesn’t exist in the File Name edit box and chooses OK. The message informs
the user the file can’t be found and asks the user to make sure they entered the
correct path and file name.
ofHideReadOnly If True, this option hides the Read Only check box in the dialog box.
ofNoChangeDir If True, this option sets the current directory to whatever the current directory
was when the dialog box first appeared and ignores any directory changes the
user made while using the dialog box.
ofNoReadOnlyReturn If True, a message box appears informing the user if the selected file is read-only.
ofNoTestFileCreate This option applies only when the user wants to save a file on a create-no-modify
network share point, which can’t be opened again once it has been opened. If
ofNoTestFileCreate is True, your application won’t check for write protection, a full
disk, an open drive door, or network protection when saving the file because
doing so creates a test file. Your application will then have to handle file
operations carefully so that a file isn’t closed until you really want it to be.
ofNoValidate If True, this option doesn’t prevent the user from entering invalid characters in a
file name. If ofNoValidate is False and the user enters invalid characters for a file
name in the File Name edit box, a message dialog box appears informing the user
the file name contains invalid characters.
Value Meaning
ofOverwritePrompt If True, this option displays a message dialog box if the user attempts to save a file
that already exists. The message informs the user the file exists and lets the user
choose to overwrite the existing file or not.
ofReadOnly If True, the Read Only check box is checked when the dialog box is displayed.
ofPathMustExist If this option is True, the user can type only existing path names as part of the file
name in the File Name edit box. If the user enters a path name that doesn’t exist, a
message box appears informing the user that the path name is invalid.
ofShareAware If True, the dialog box ignores all sharing errors and returns the name of the
selected file even though a sharing violation occurred. If ofShareAware is False, a
sharing violation results in a message box informing the user of the problem.
ofShowHelp If True, this option displays a Help button in the dialog box.
The default value is [ ], the empty set, meaning that none of the options are in effect.
Example
This example uses an Open dialog box and a button on a form. The code forces the user
to enter valid file name characters, prevents the read-only check box from appearing in
the dialog box, and let’s the user choose to overwrite a file if the user selects a file that
doesn’t exist; the selected file name appears in a label on the form:
procedure TForm1.Button1Click(Sender: TObject);
begin
OpenDialog1.Options := [ofNoValidate, ofHideReadOnly, ofCreatePrompt];
if OpenDialog1.Execute then
Label1.Caption := OpenDialog1.FileName;
end;
Value Meaning
frDisableMatchCase When True, the Match Case check box is dimmed and users cannot check it. When
it is False, users can check the Match Case check box.
frDisableUpDown When True, the Direction Up and Down buttons are dimmed and the user cannot
select either of them. When it is False, users can select one of the Direction Up and
Down buttons.
frDisableWholeWord When True, the Match Whole Word check box is dimmed and user cannot select it.
When it is False, users can check the check box.
frDown When True, the Down button is selected in the dialog box and the search direction
is down. When frDown is False, the Up button is selected, and the search direction
is up. frDown can be set a design time, or users can change its value at run time
when they use the dialog box.
For outlines
Declaration
property Options: TOutlineOptions;
The Options property determines how the items in an outline are drawn. These are the
possible values that can be contained in the Options set:
Value Meaning
ooDrawTreeRoot The first item (Index value of 1) is connected to the root item by the outline tree.
This means that the tree will extend from the top of the outline to all the first level
items. Without ooDrawTreeRoot, all first level items appear leftmost in the outline,
not connected by the tree.
Value Meaning
ooDrawFocusRect The outline draws a focus rectangle around the selected item.
ooStretchBitmaps The outline stretches the standard bitmaps (PictureLeaf, PictureOpen, PictureClosed,
PicturePlus, PictureMinus) to fit in the size of the item, determined by the size of the
Font of the Text. Without ooStretchBitmap, the bitmaps won’t be stretched. They will
be cropped if larger than the height of the item text, or won’t fill up the entire item
space if smaller than the text.
Example
The following code draws the tree of the outline to the root (extending from the first
level items to the top of the outline).
Outline1.Options := [ooDrawTreeRoot];
See also
OutlineStyle property, Style property
Value Meaning
goFixedHorzLine When True, horizontal lines appear between the rows within nonscrolling regions.
goFixedVertLine When True, vertical lines appear between the columns within nonscrolling
regions.
goHorzLine When True, horizontal lines appear between the rows.
goVertLine When True, vertical lines appear between the columns.
goRangeSelect When True, the user can select a range of cells at one time. When goEditing is True,
the user can no longer select a range of cells.
goDrawFocusSelected When True, the cell with the focus is colored the same as other cells in a selected
block are colored. When False, the cell with the focus remains the color of all
unselected cells, the color specified with the grid Color property.
goRowSizing When True, rows can be resized individually except for fixed or nonscrolling rows.
goColSizing When True, columns can be resized individually except for fixed or nonscrolling
columns.
goRowMoving When True, the user can move a row to a new location in the grid using the mouse.
goColMoving When True, the user can move a column to a new location in the grid using the
mouse.
goEditing When True, the user can edit the text in the grid. When goEditing is True, the user
cannot select a range of cells at one time.
goAlwaysShowEditor When True, the grid is in automatic edit mode if goEditing is also True. When the
grid is in automatic edit mode, the user does not have to press Enter or F2 before
editing the contents of a cell. When goAlwaysShowEditor is False and goEditing is
True, the user must press Enter or F2 before editing the contents of a cell. If
goEditing is False, setting goAlwaysShowEditor to True has no effect.
Value
goTabs
Meaning
+
When True, the user can use the Tab and Shift-Tab keys to move from column to
goRowSelect
column in the grid.
+
When True, the user can select only whole rows at a time instead of individual
cells.
goThumbTracking +
When True, the contents of the grid scrolls while the user is moving the thumb tab
of the grid scroll bar. When False, the contents of the grid doesn’t scroll until the
user releases the thumb tab in its new position.
+
This code changes the look of the grid; only horizontal lines appear in both the body of +
Example
the grid and in the nonscrolling regions when the user clicks the ChangeGridStyle button:
procedure TForm1.ChangeGridStyleClick(Sender: TObject); +
begin
DrawGrid1.Options := [goFixedHorzLine, goHorzLine];
end;
+
+
For data grids
+
Declaration
property Options: TDBGridOptions;
+
These are the possible values that can be included in the Options set for the data grid
control:
+
Value Meaning
+
dgEditing O
When True, allows the user to edit data in the data grid. When the ReadOnly
property is True and dgEditing is True, users can still use the Insert key to insert a
blank row, or press the Down Arrow key when positioned at the bottom of the grid
to append a blank row, although they won’t be able to enter text in the new row.
dgAlwaysShowEditor When True, the grid is in automatic edit mode as long as gdEditing is also True.
When the grid is in automatic edit mode, the user does not have to press Enter or
F2 before editing the contents of a cell. When gdAlwaysShowEditor is False and
gdEditing is True, the user must press Enter or F2 before editing the contents of a
cell. If gdEditing is False, setting gdAlwaysShowEditor to True has no effect.
dgTitles When True, the column titles are visible.
dgIndicator When True, a small pointer is visible that indicates which column is the current
one.
dgColumnResize When True, the columns can be resized. A column can’t be resized, however, until
its field has been added to the grid. To add a field to the grid, choose Add from
the Fields editor.
dgColLines When True, lines between the columns appear.
dgRowLines When True, lines between the rows appear.
dgTabs When True, users press the Tab key and the Shift-Tab keys to move among the
columns of the data grid.
dgRowSelect When True, the user can select whole rows only instead of individual cells.
dgAlwaysShowSelection When True, the cell selected in the grid continues to display as selected even if the
data grid doesn’t have the focus.
Value Meaning
dgConfirmDelete When True, a message box appears if the user uses Ctrl+Delete to delete a row in
the grid. The message box asks for confirmation that the row should really be
deleted.
dgCancelOnExit When True, if an insert is pending and no modifications were made by the user,
the insert will be cancelled when the user exits the grid. This prevents the
inadvertent posting of partial or blank records.
Example
This line of code displays column titles, makes the column indicator visible, and permits
the user to edit the data displayed in the data grid:
procedure TForm1.FormClick(Sender: TObject);
begin
DBGrid1.Options := [dgIndicator, dgEditing, dgTitles];
end;
See also
ReadOnly property
Declaration
property Options: TDBLookupListOptions;
The Options property determines how multiple columns in database lookup combo
boxes and database lookup list boxes appear. These are the possible values that can be
part of the Options set:
Value Meaning
loColLines When True, lines separate the columns displayed in the control. When False, no lines appear
between the columns.
loRowLines When True, lines separate the rows displayed in the control. When False, no lines appear
between the rows.
loTitles When True, the field names appear as titles above the columns in the control. When False,
no titles appear.
Example
This code displays three fields in a database lookup list box, displays the field names as
titles for the columns, and separates the columns with lines:
procedure TForm1.FormCreate(Sender: TObject);
begin
DBLookupList1.LookupDisplay := 'Company;City;Country';
See also
Chr function
Orientation property
Applies to
TPrinter object
Declaration
property Orientation: TPrinterOrientation;
Run-time only. The value of the Orientation property determines if the print job prints
vertically or horizontally on a page. These are the possible values:
Value Meaning
poPortrait The print job prints vertically on the page.
poLandscape The print job prints horizontally on the page.
Example
This example uses two radio buttons on a form named Landscape and Portrait. The form
also includes a button. When the user selects an orientation by clicking one of the radio
buttons and then clicks the button to print one line of text, the print job prints using the
selected orientation:
procedure TForm1.Button1Click(Sender: TObject);
begin
Printer.BeginDoc;
Printer.Canvas.TextOut(100,100,'Hi there');
Printer.EndDoc;
end;
procedure TForm1.PortraitClick(Sender: TObject);
begin
Printer.Orientation := poPortrait;
end;
procedure TForm1.LandscapeClick(Sender: TObject);
begin
Printer.Orientation := poLandscape;
end;
See also
Printer variable
+
osTreePictureText Displays outline tree, open picture, closed picture, leaf picture, and item text.
osTreeText Displays outline tree and item text.
Example
The following code displays pictures only if they are monochrome. The first choice is
+
Open and Closed pictures. If they aren’t monochrome, the code tests Plus and Minus
pictures. The final resort is to simply display text.
+
with Outline1 do
if (PictureOpen.Monochrome and PictureClosed.Monochrome) then
O
OutlineStyle := osPictureText
else if (PicturePlus.Monochrome and PictureMinus.Monochrome) then
OutlineStyle := osPlusMinusText
else OutlineStyle := osText;
The Output variable is a write-only file associated with the operating system’s standard
output file, which is usually the display.
In many of Delphi's standard file-handling routines, the file variable parameter can be
omitted. Instead the routine operates on the Input or Output file variable. The following
standard file-handling routines operate on the Output file when no file parameter is
specified:
• Write
• Writeln
Since Windows does not support text-oriented input and output, Input and Output files
are unassigned by default in a Windows application. Any attempt to read or write to
them will produce an I/O error.
If the application uses the WinCrt unit, Input and Output will refer to a scrollable text
window.
See also
Input variable, TextFile type
Overload property
Applies to
TStoredProc component
Declaration
property Overload: Word;
Oracle servers allow overloading of stored procedures in an Oracle package; that is,
different procedures with the same name.
Set the Overload property to specify the procedure to execute on an Oracle server. If
Overload is zero (the default), there is assumed to be no overloading. If Overload is one
(1), then Delphi will execute the first stored procedure with the overloaded name; if it is
two (2), it will execute the second, and so on.
See also
StoredProcName property
Owner property
Applies to
All components
Declaration
property Owner: TComponent;
Pack method
Applies to
TList object
Declaration
procedure Pack;
The Pack method deletes all nil items from the list of pointers kept by the List property of
a list object. Items become nil when the Delete or Remove’ method has been called to
delete them from the list.
Example
This example assumes there are two edit box controls on the form. The code creates a list
object and adds two strings to it. The second string in the list is a nil string. The code
counts the number of strings in the list and displays the number in the Edit1 control. The
code then packs the list, removing the nil string, and counts the strings in the list again.
The second count displays in the Edit2 control:
procedure TForm1.FormCreate(Sender: TObject);
var
MyList: TList;
I: Integer;
Buffer: string;
begin
MyList := TList.Create; {Create a list of TList}
MyList.Add(PChar('Another string')); {Add a string}
MyList.Add(PChar(NIL)); {Add a Nil string}
Str(MyList.Count, Buffer);
Edit1.Text := Buffer; {Put count into Edit1}
Mylist.Pack; {Pack the list.}
Str(MyList.Count, Buffer);
Edit2.Text := Buffer; {Put count into Edit2}
MyList.Free; {Free memory for list}
end;
See also
Expand method, Remove method, Capacity property
PageHeight property
Applies to
TPrinter object
Declaration
property PageHeight: Integer;
Run-time and read only. The PageHeight property contains the height of the currently
printing page in pixels.
Example
This code displays the page height of the currently printing page in an edit box.
To run this code successfully, you must add Printers to the uses clause of your unit.
Edit1.Text := IntToStr(Printer.PageHeight);
See also
PageNumber property, PageWidth property, Printer variable
See also
ActivePage property, TTabSet component
PageNumber property
Applies to
TPrinter object
Declaration
property PageNumber: Integer;
Run-time and read only. The PageNumber property contains the number of the current
page. Each time an application calls the NewPage method, NewPage increments the value
of PageNumber.
Example
This example uses a button on a form. When the user clicks the button, one line of text is
printed on six separate pages. As each page is printed, a message indicating the number
of the page being printed appears on the form.
To run this example successfully, you must add Printers to the uses clause of your unit.
procedure TForm1.Button1Click(Sender: TObject);
var
I, X, Y: Integer;
begin
Printer.BeginDoc;
X := 10;
Y := 10;
for I := 1 to 6 do
begin
Printer.Canvas.TextOut(100, 100, 'Object Pascal is great');
Canvas.TextOut(X, Y, 'Printing page ' + IntToStr(Printer.PageNumber));
Printer.NewPage;
Y := Y + 20;
end;
Printer.EndDoc;
end;
See also
NewPage method, Printer variable
Pages property
Applies to
TNotebook, TTabbedNotebook components
Declaration
property Pages: TStrings;
The Pages property contains the strings that identify the individual pages of the
+
notebook or tabbed notebook control. Both these controls create a separate page for each
string in the Pages property. For example, if Pages contains three strings, First, Second,
+
and Third, the control has three separate pages. +
You can access the various pages in a notebook or tabbed notebook control with either
the ActivePage or PageIndex property. +
Example
The following code ensures that the Pages of Notebook1 correspond with the value of the
+
Tabs property of TabSet1. +
Notebook1.Pages := TabSet1.Tabs;
+
See also
TTabSet component +
PageWidth property
+
Applies to
+
TPrinter object +
Declaration +
property PageWidth: Integer;
Run-time and read only. The PageWidth property contains the value of width of the
+
currently printing page in pixels.
+
Example
The code uses an edit box on a form. The code creates a printer object and displays the P
current width of a page in pixels in the edit box when the form first appears.
To run this example, you must add the Printers unit to the uses clause of your unit.
procedure TForm1.FormCreate(Sender: TObject);
begin
Edit1.Text := IntToStr(Printer.PageWidth) + ' pixels';
end;
See also
PageHeight property, PageNumber property, Printer variable
Palette property
Applies to
TBitmap object
Declaration
property Palette: HPalette;
The Palette property controls a bitmap’s color mapping. The Palette of a bitmap contains
up to 256 colors that can be used to display the bitmap onscreen.
If the bitmap is drawn by an application running in the foreground, as many colors of
Palette as will be added to the Windows system palette. Any additional colors will be
mapped to the existing colors of the system palette. If the bitmap is drawn by an
application running in the background and another application has loaded the system
palette with its own colors, the bitmap’s colors will be mapped to the system palette.
Example
The following code selects the Palette from Form1 for Form2.
SelectPalette(Form2.Canvas.Handle, Form1.Canvas.Palette, True);
ParamBindMode property
Applies to
TStoredProc component
Declaration
property ParamBindMode; TParamBindMode;
ParamBindMode determines how the elements of the Params array will be matched with
stored procedure parameters. If ParamBindMode is set to pbByName (the default),
parameters will be bound based on their names in the stored procedure. If
ParamBindMode is set to pbByNumber, parameters will be bound based on the order in
which they are defined in the stored procedure. Use this setting if you are building your
parameters list, and you don’t want to use the parameter names defined in the stored
procedure.
Example
ParamBindMode := pbByName;
ParamByName method
Applies to
TParams object; TQuery, TStoredProc component
Example
begin
if ParamCount = 0 then
See also
ParamStr function
ParamCount property
Applies to
TQuery, TStoredProc component
Example
for I := 0 to Query1.ParamCount - 1 do
Query1.Params[I].AsInteger := I;
See also
Params property
Example
{ Set all parameters to an empty string }
with StoredProc1 do
for I := 0 to ParamCount - 1 do
Param[I].AsString := ‘’;
Example
For example, suppose a TQuery component named Query2 has the following statement
for its SQL property:
INSERT
INTO COUNTRY (NAME, CAPITAL, POPULATION)
VALUES (:Name, :Capital, :Population)
An application could use Params to specify the values of the parameters as follows:
Query2.Params[0].AsString := 'Lichtenstein';
Query2.Params[1].AsString := 'Vaduz';
Query2.Params[2].AsInteger := 420000;
These statements would bind the value “Lichtenstein” to the :Name parameter,
“Vaduz” to the :Capital parameter, and 420000 to the :Population parameter.
Example
var
I: Word;
Y: Integer;
begin
Y := 10;
for I := 1 to ParamCount do begin
Canvas.TextOut(5, Y, ParamStr(I));
Y := Y + Canvas.TextHeight(ParamStr(I)) + 5;
end;
end;
See also
ParamCount function
Example
To set up the form for this example, put a group box on the form and add a radio button
to the group box. Put two labels and a button on the form. This code displays the name
of the parent of the radio button and the class name of the owner of the radio button in
the captions of the two labels when the user clicks the button:
procedure TForm1.Button1Click(Sender: TObject);
begin
Label1.Caption := RadioButton1.Parent.Name + ' is the parent';
Label2.Caption := RadioButton1.Owner.ClassName +
' is the class name of the owner';
end;
This example uses a button and a group box on a form. When the user clicks the button,
the button moves inside the group box, because the group box is now the parent of the
button.
procedure TForm1.Button1Click(Sender: TObject);
begin
Button1.Parent := GroupBox1;
end;
See also
Controls property, Owner property
Declaration
property Parent: TMenuItem;
Run-time and read only. The Parent property of a menu item identifies the parent menu
item of this menu item.
Example
This example assumes there are two edit boxes on a form as well as a main menu that
contains menu items. One of the menu items has Save as the value of its Caption
property, so the value of its Name property is Save1. The code displays the name of the
parent of the Save1 menu item in the Edit1 control, and it displays the class name of the
parent in the Edit2 control when the form first appears.
procedure TForm1.FormCreate(Sender: TObject);
begin
Edit1.Text := Save1.Parent.Name;
Edit2.Text := Save1.Parent.ClassName;
end;
Declaration
property ParentColor: Boolean;
The ParentColor property determines where a control looks for its color information. If
ParentColor is True, the control uses the color in its parent component’s Color property. If
ParentColor is False, the control uses its own Color property. Except for the radio group,
database radio group, label and database text controls, the default value is False.
By using ParentColor, you can ensure that all the controls on a form have a uniform
appearance. For example, if you change the background color of your form to gray, by
default, the controls on the form will also have a gray background.
To specify a different color for a particular control, specify the desired color as the value
of that control’s Color property, and ParentColor becomes False automatically.
Example
This code uses a label control and a timer component on the form. When the OnTimer
event occurs, the label turns red if the label’s ParentColor property is True. If the
ParentColor property is False, ParentColor is set to True. The result is the label flashes red
on and off. Every other time an OnTimer event occurs, the label turns red. The other
times, the label assumes the color of its parent, Form1.
procedure TForm1.Timer1Timer(Sender: TObject);
begin
if Label1.ParentColor then
Label1.Color := clRed
else
Label1.ParentColor := True;
end;
See also
Color property, Parent property, ParentFont property
ParentCtl3D property
Applies to
TCheckBox, TComboBox, TDBCheckBox, TDBComboBox, TDBEdit, TDBGrid, TDBImage,
TDBLookupCombo, TDBLookupList, TDBListBox, TDBNavigator, TDBMemo,
TDBRadioGroup, TDirectoryListBox, TDrawGrid, TDriveComboBox, TEdit, TFileListBox,
TFilterComboBox, TGroupBox, TListBox, TMaskEdit, TMemo, TNotebook, TOLEContainer,
TOutline, TPanel, TRadioButton, TScrollBox, TStringGrid components
Declaration
property ParentCtl3D: Boolean;
The ParentCtl3D property determines where a component looks to determine if it
should appear three dimensional. If ParentCtl3D is True, the component uses the
dimensionality of its parent component’s Ctl3D property. If ParentCtl3D is False, the
control uses its own Ctl3D property. The default value is True.
By using ParentCtl3D, you can ensure that all the components on a form have a uniform
appearance. For example, if you want all components on a form to appear three