TEAMFLY
John Ayres
Wordware Publishing, Inc.
Library of Congress Cataloging-in-Publication Data
Ayres, John.
Tomes of Delphi: Win32 Core API Windows 2000 edition / by John Ayres.
p. cm.
Includes bibliographical references and index.
ISBN 1-55622-750-7 (pbk.)
1. Microsoft Win32. 2. Delphi (Computer file). I. Title.
QA76.76.O63 A97 2001 2001046842
005.265 dc21 CIP
Copyright © 2002, Wordware Publishing, Inc.
All Rights Reserved
2320 Los Rios Boulevard
Plano, Texas 75074
No part of this book may be reproduced in any form or by
any means without permission in writing from
Wordware Publishing, Inc.
Printed in the United States of America
ISBN 1-55622-750-7
10987654321
0110
Delphi is a trademark of Borland Software Corporation in the United States and other countries.
Windows is a registered trademark of Microsoft Corporation in the United States and/or other countries.
Other product names mentioned are used for identification purposes only and may be trademarks of their respective companies.
All inquiries for volume purchases of this book should be addressed to Wordware Publishing, Inc., at the above
address. Telephone inquiries may be made by calling:
(972) 423-0090
Praise for The Tomes of Delphi 3: Win32 Core API
“The Tomes of Delphi is the definitive reference for the Win32 API expressed in the
Bob Swart (a.k.a. “Dr. Bob”), Author, trainer, consultant
***************************
“Not only were these the first Delphi books to concentrate on API-level programming,
they set the standard for all future Delphi API books.”
Alan C. Moore, Contributing Editor
Delphi Informant Magazine
Dedication
I would like to dedicate this book to the following people and/or deities who have had a
profound influence in my life: First, to God, whom I’ve been growing much closer to
these last few years, for giving me the intelligence to wade through the confusing and
sometimes maddening sea of Windows API documentation and make sense of it all; sec
-
ond, to my family, for putting up with my lack of participation in family activities during
this project; and finally, but most of all, to my wife and soulmate, Marci, who made sure I
had clothes to wear in the morning and food in the evening, fixed my lunches, and gener
-
ally took up all of my housework responsibilities so I could concentrate on the book. She
encouraged me and prodded me along when the weight of this project became unbearable,
and because of this she is directly responsible for this work being completed. She is a very
inspiring task master; cracking the whip to bring me in line when I would have rather been
playing X-Wing vs. Tie Fighter. I am unworthy of such a devoted and loving wife, and I
thank God every day for providing me with such a perfect companion. Baby, this one’s
for you.
Contents
Foreword xvi
Acknowledgments xviii
Introduction xix
Chapter 1 Delphi and the Windows API 1
Windows Data Types 1
Handles 3
Message Processing Functions 62
v
BroadcastSystemMessage 63
CallNextHookEx 65
CallWindowProc 66
DefFrameProc 68
DefMDIChildProc 73
DefWindowProc 74
DispatchMessage 75
GetMessage 76
GetMessageExtraInfo 79
GetMessagePos 80
GetMessageTime 81
GetQueueStatus 81
InSendMessage 83
PeekMessage 84
PostMessage 86
PostQuitMessage 89
PostThreadMessage 89
RegisterWindowMessage 91
ReplyMessage 93
SendMessage 94
SendMessageCallback 95
SendMessageTimeout 97
SendNotifyMessage 100
SetMessageExtraInfo 102
SetWindowsHookEx 103
WH_CALLWNDPROC Hook Function 105
WH_CALLWNDPROCRET Hook Function 106
WH_CBT Hook Function 107
CopyMemory 132
FillMemory 133
GetProcessHeap 134
GlobalAlloc 135
GlobalDiscard 136
GlobalFlags 137
GlobalFree 138
GlobalHandle 138
GlobalLock 139
GlobalMemoryStatus 140
GlobalReAlloc 142
GlobalSize 145
GlobalUnlock 145
HeapAlloc 146
HeapCreate 148
HeapDestroy 150
HeapFree 150
HeapReAlloc 151
HeapSize 152
IsBadCodePtr 153
IsBadReadPtr 154
IsBadStringPtr 155
IsBadWritePtr 156
MoveMemory 157
VirtualAlloc 159
VirtualFree 163
VirtualProtect 164
VirtualQuery 166
ZeroMemory 168
Chapter 5 Dynamic-Link Library Functions 169
Delphi vs. the Windows API 192
Process and Thread Functions 192
CreateEvent 194
CreateMutex 197
CreateProcess 200
CreateSemaphore 206
CreateThread 210
DeleteCriticalSection 211
DuplicateHandle 211
EnterCriticalSection 214
ExitProcess 215
ExitThread 216
GetCurrentProcess 217
GetCurrentProcessId 217
GetCurrentThread 218
GetCurrentThreadId 218
GetExitCodeProcess 219
GetExitCodeThread 220
GetPriorityClass 221
GetThreadPriority 223
GetWindowThreadProcessId 225
InitializeCriticalSection 226
InterlockedDecrement 228
InterlockedExchange 230
InterlockedIncrement 231
LeaveCriticalSection 232
OpenEvent 232
OpenMutex 233
OpenProcess 234
viii
SetTimer 264
Chapter 8 Error Functions 267
Error Descriptions 267
Audible Error Cues 268
Delphi vs. the Windows API 269
Error Functions 270
Beep 270
ExitWindows 271
ExitWindowsEx 272
FatalAppExit 273
GetLastError 274
MessageBeep 275
SetLastError 276
Chapter 9 Graphical Device Interface Functions 279
Device Independence 279
Device Contexts 280
Device Context Types 280
Screen, Window, and Client Area Device Contexts 282
Contents
n
ix
Coordinate Systems 283
Mapping Logical Coordinates into Device Coordinates 284
Mapping Modes 284
Problems with Logical Coordinate Mapping 288
Delphi vs. the Windows API 289
Graphical Device Interface Functions 289
ChangeDisplaySettings 290
ClientToScreen 294
CreateCompatibleDC 296
Graphical Objects 345
Pens and Brushes 346
Delphi vs. the Windows API 346
Painting and Drawing Functions 347
Arc 348
BeginPaint 351
Chord 352
CreateBrushIndirect 354
x
n
Contents
TEAMFLY
Team-Fly
®
CreateHatchBrush 357
CreatePatternBrush 358
CreatePen 360
CreatePenIndirect 362
CreateSolidBrush 364
DeleteObject 365
DrawCaption 366
DrawEdge 367
DrawFocusRect 370
DrawFrameControl 371
DrawState 375
Ellipse 379
EndPaint 380
EnumObjects 381
ExtCreatePen 383
ExtFloodFill 387
FillPath 388
FillRect 389
FillRgn 391
FrameRect 391
FrameRgn 392
GetBkColor 394
Polyline 433
PolylineTo 434
PolyPolygon 435
PolyPolyline 437
Rectangle 438
RoundRect 440
SelectObject 442
SetBkColor 443
SetBkMode 444
SetBoundsRect 444
SetBrushOrgEx 446
SetMiterLimit 446
SetPixel 447
SetPixelV 449
SetPolyFillMode 449
SetROP2 450
StrokeAndFillPath 452
StrokePath 453
Chapter 11 Region and Path Functions 455
Regions and Paths 455
Regions 455
Paths 458
Special Effects 458
Delphi vs. the Windows API 460
Region and Path Functions 461
AbortPath 462
BeginPath 463
CloseFigure 463
CombineRgn 465
CopyRect 468
PathToRegion 507
PtInRect 509
PtInRegion 509
PtVisible 510
RectInRegion 511
RectVisible 511
SelectClipPath 512
SelectClipRgn 516
SetRect 519
SetRectEmpty 520
SetRectRgn 521
SetWindowRgn 522
SubtractRect 525
UnionRect 526
WidenPath 527
Chapter 12 Bitmap and Metafile Functions 529
Bitmaps 529
Device-dependent Bitmaps 530
Device-independent Bitmaps 530
Bitmap Operations 530
Metafiles 537
Enhanced Metafiles 537
Delphi vs. the Windows API 537
Bitmap and Metafile Functions 538
BitBlt 539
CloseEnhMetaFile 541
CopyEnhMetaFile 541
CopyImage 542
CreateBitmap 545
CreateBitmapIndirect 548
Font Families 609
Character Sets 610
Character Dimensions 611
The Windows Font Table 611
Font Embedding 612
Delphi vs. the Windows API 617
Text Output Functions 618
AddFontResource 619
CreateFont 619
CreateFontIndirect 626
CreateScalableFontResource 632
DrawText 634
DrawTextEx 638
EnumFontFamilies 642
EnumFontFamiliesEx 647
GetCharABCWidths 653
GetCharWidth 655
GetFontData 656
GetGlyphOutline 657
GetKerningPairs 662
GetOutlineTextMetrics 664
GetRasterizerCaps 679
GetTabbedTextExtent 680
GetTextAlign 681
GetTextCharacterExtra 682
GetTextColor 683
xiv
n
Contents
GetTextExtentExPoint 683
understanding of the Windows API. However, there comes a time in the course of most
application development projects when you simply have to turn to the Windows API in
order to solve a particular problem. Usually this happens because a tool you are using
does not have a feature you need, or because the feature is not implemented properly. In
such cases, you have to turn to the Windows API in order to implement the feature
yourself.
2. Another reason to use the Windows API surfaces when you want to create a component or
utility that others can use. If you want to build a component, ActiveX control, or simple
utility that will perform a useful function needed by other developers or power users, then
you probably will need to turn to the Windows API. Without recourse to the Windows
API, such projects are usually not feasible.
3. The final and best reason for learning the Windows API is that it helps you see how you
should architect your application. We have many high-level tools these days that let us
build projects at a very remote, and powerful, level of abstraction. However, each of these
tools is built on top of the Windows API, and it is difficult, if not impossible, to under
-
stand how to use them without understanding the architecture on which they are founded.
If you understand the Windows API then you know what the operating system can do for
you, and how it goes about providing that service. With this knowledge under your belt,
you can use high-level tools in an intelligent and thoughtful manner.
xvi
I am particularly pleased to see the publication of Wordware’s books on the Windows API
because they are built around the world’s greatest development tool: Delphi. Delphi gives
you full access to the entire Windows API. It is a tool designed to let you plumb the
depths of the operating system, to best utilize the features that have made Windows the
preeminent operating system in the world today.
Armed with these books on the Windows API, and a copy of Delphi, you can build any
type of application you desire, and can be sure that it is being constructed in the optimal
possible manner. No other compiler can bring you closer to the operating system, nor can
any other compiler let you take better advantage of the operating system’s features. These
Debbie Vilbig and Darla Corley, for giving me the time to learn Delphi and write a call
tracking application when I should have been doing real work.
Sarah Miles, for providing me with a short-term loan that allowed me to buy the machine
that this book was written on.
Suzy Weaver and Brian Donahoo for trusting a former employee and providing a nice,
quiet place to work on the weekends.
Of course, no acknowledgment would be complete without thanking the Delphi develop
-
ment staff at Borland for giving all of us such an awesome development tool.
xviii
Introduction
The Windows programming environment. No other operating system in history has caused
so much controversy or confusion among the programming industry. Of course, no other
operating system in history has made so many millionaires either. Like it or not, Windows
is here to stay. It’s hard to ignore such a large user base, and there are few job opportuni
-
ties anymore that do not require the programmer to have knowledge of the Windows
environment.
In the beginning, a programmer’s only choice of tools for creating Windows applications
was C/C++. The age of this language has resulted in a wealth of Windows API documen-
tation, filled with abstract and incomplete information, and examples that are as esoteric
and arcane as the C language itself. Then along came Delphi. A new era in Windows pro-
gramming was born, with the ability to easily create complex and advanced Windows
applications with a turnaround time unheard of previously. Although Delphi tries its best
to insulate the programmer from the underlying Windows architecture, Delphi program-
mers have found that some programming obstacles simply cannot be overcome without
using low-level Windows API functions. Although there have been a few books that
touched on the subject of using Windows API functions in Delphi, none have ever
discussed the issue in depth. There are numerous magazine articles that describe very spe-
cific subsets of the API, but unless the Delphi programmer had a background in C, and the
Chapter 4: Memory Management Functions
Only the most simplistic of programs will not need access to dynamically allocated mem-
ory. This chapter covers functions used to allocate and release system and virtual memory.
Examples demonstrate heap management routines, virtual memory allocation, and retriev-
ing information about allocated memory blocks.
Chapter 5: Dynamic-Link Library Functions
Dynamic-link libraries are at the core of the Windows operating system architecture, and
Windows could not run without them. This chapter covers functions that allow an applica
-
tion to load and import functions from a DLL. Examples include explicitly loading a DLL
and importing its functions at run time, and providing a user-defined DLL entry point.
Chapter 6: Process and Thread Functions
Multitasking environments allow an application to spawn other applications, or even
another thread of execution within itself. This chapter covers the functions used to create
and manage threads and processes. Examples include creating and destroying a thread,
launching an external process, creating a mutex, and using thread events.
Chapter 7: Timer Functions
Setting up a timer to repeatedly call a function is the only solution for some programming
issues. This chapter covers essential functions used to create a low-level Windows timer.
Examples include utilizing the high-resolution timer to measure code performance.
xx
n
Introduction
TEAMFLY
Team-Fly
®
Chapter 8: Error Functions
Error management is always an issue with any programming project. This chapter covers
functions used in debugging and error management. Examples include displaying system-
defined error strings, and user-defined error values.
Chapter 9: Graphical Device Interface Functions
The basic Graphical Device Interface functions are integral to any graphics programming
in Windows. This chapter covers functions used to manipulate and create device contexts.
Examples include creating various types of device contexts, retrieving device capabilities,
and changing the display mode.
Chapter 10: Painting and Drawing Functions
xxi
function HelloThere(Info: string): Integer;
begin
ShowMessage(Info);
end;
In order to be consistent with other works on Delphi programming, the example code
follows the Borland coding conventions, which include using mixed case for variable
names and identifiers, lowercase for reserved words, and nested code indented two spaces
per level. Any constants used in the code will appear in all capitals, such as TRUE and
FALSE. Also, notice that the name of the unit that contains an individual function is
located on the same line as the function name. This unit must be included in the Uses
clause of any unit in which this function is used. However, most of the functions covered
in this series are located in the Windows.pas file, which is automatically added to the Uses
clause by Delphi. In addition, when the text refers to a window, as in a visual object on the
screen, the word “window” will begin with a lowercase letter. When the text refers to
Windows, as in the operating system, the word “Windows” will be capitalized.
Function Descriptions
The Windows API function descriptions have been laid out in a format that provides an
increasing amount of detail to the reader. This should allow the reader to quickly glance at
a function description for a simple reminder of required parameters, or to read further for
a detailed explanation of the function, an example of its use, and any acceptable constant
values used in a parameter.
Each function description includes the exact syntax found in the Delphi source code, a
description of what the function does, a detailed list and description of the function’s
parameters, the value returned from the function, a list of related functions, and an exam-
ple of its use. Any defined constants used in a function parameter are found in tables that
follow the example, so that the descriptive text of the function is not broken by a distrac
-
tion, and all of the constants are available in one place for easy perusal. Some tables may
be repeated under various functions that use the same parameters. This was done to elimi
out in a logical order of progression, starting with the most fundamental Windows API
functions and working towards the more specialized functions.
If you are looking for an introduction to Delphi programming, or a step-by-step Windows
programming tutorial, there are plenty of other fine books out there to get you started.
However, if you’ve got a nasty problem whose only hope of salvation is using the Win-
dows API, if you want to extend the functionality of Delphi components and objects, or
you want a down-and-dirty, no-holds-barred collection of Delphi Win32 API program-
ming examples, then this book is for you. You will not find a more complete and accurate
guide to the Win32 API for the Delphi programmer.
Introduction
n
xxiii