.NET Framework Solutions: In Search of theLost Win32 API

quiverlickforkΛογισμικό & κατασκευή λογ/κού

2 Νοε 2013 (πριν από 4 χρόνια και 8 μήνες)

162 εμφανίσεις

.NET Framework
Solutions:In Search of
the Lost Win32 API
John Paul Mueller
San Francisco • London
4134FM.qxd 8/27/02 11:34 AM Page iii
4134FM.qxd 8/27/02 11:34 AM Page ii
.NET Framework
4134FM.qxd 8/27/02 11:34 AM Page i
4134FM.qxd 8/27/02 11:34 AM Page ii
.NET Framework
Solutions:In Search of
the Lost Win32 API
John Paul Mueller
San Francisco • London
4134FM.qxd 8/27/02 11:34 AM Page iii
Associate Publisher: Joel Fuggazzotto
Acquisitions and Developmental Editor: Denise Santoro Lincoln
Editors: Judy Flynn, William Rodarmor
Production Editor: Kylie Johnston
Technical Editor: Ross Russell Mullen
Graphic Illustrator: Jeff Wilson, Happenstance Type-O-Rama
Electronic Publishing Specialists: Jill Niles, Judy Fung, Scott Benoit
Proofreaders: Laurie O’Connell, Dave Nash, Nancy Riddiough, Monique van den Berg
Indexer: Lynnzee Elze
CD Coordinator: Dan Mummert
CD Technician: Kevin Ly
Cover Designer: Caryl Gorska/Gorska Design
Cover Photographers: Peter Samuels, Tony Stone
Copyright © 2002 SYBEX Inc., 1151 Marina Village Parkway, Alameda, CA 94501. World rights reserved. The author(s) created reusable
code in this publication expressly for reuse by readers. Sybex grants readers limited permission to reuse the code found in this publication or
its accompanying CD-ROM so long as (author(s)) are attributed in any application containing the reusable code and the code itself is never
distributed, posted online by electronic transmission, sold, or commercially exploited as a stand-alone product. Aside from this specific
exception concerning reusable code, no part of this publication may be stored in a retrieval system, transmitted, or reproduced in any way,
including but not limited to photocopy, photograph, magnetic, or other record, without the prior agreement and written permission of the
Library of Congress Card Number: 2002108076
ISBN: 0-7821-4134-X
SYBEX and the SYBEX logo are either registered trademarks or trademarks of SYBEX Inc. in the United States and/or other countries.
Screen reproductions produced with FullShot 99. FullShot 99 © 1991-1999 Inbit Incorporated. All rights reserved.
FullShot is a trademark of Inbit Incorporated.
The CD interface was created using Macromedia Director, COPYRIGHT 1994, 1997-1999 Macromedia Inc. For more information on
Macromedia and Macromedia Director, visit
TRADEMARKS: SYBEX has attempted throughout this book to distinguish proprietary trademarks from descriptive terms by following
the capitalization style used by the manufacturer.
The author and publisher have made their best efforts to prepare this book, and the content is based upon final release software whenever
possible. Portions of the manuscript may be based upon pre-release versions supplied by software manufacturer(s). The author and the
publisher make no representation or warranties of any kind with regard to the completeness or accuracy of the contents herein and accept
no liability of any kind including but not limited to performance, merchantability, fitness for any particular purpose, or any losses or damages
of any kind caused or alleged to be caused directly or indirectly from this book.
Manufactured in the United States of America
10 9 8 7 6 5 4 3 2 1
4134FM.qxd 8/27/02 11:34 AM Page iv
The media and/or any online materials accompanying this book
that are available now or in the future contain programs and/or
text files (the “Software”) to be used in connection with the book.
SYBEX hereby grants to you a license to use the Software, subject
to the terms that follow. Your purchase, acceptance, or use of the
Software will constitute your acceptance of such terms.
The Software compilation is the property of SYBEX unless other-
wise indicated and is protected by copyright to SYBEX or other
copyright owner(s) as indicated in the media files (the “Owner(s)”).
You are hereby granted a single-user license to use the Software
for your personal, noncommercial use only. You may not repro-
duce, sell, distribute, publish, circulate, or commercially exploit
the Software, or any portion thereof, without the written consent
of SYBEX and the specific copyright owner(s) of any component
software included on this media.
In the event that the Software or components include specific
license requirements or end-user agreements, statements of condi-
tion, disclaimers, limitations or warranties (“End-User License”),
those End-User Licenses supersede the terms and conditions
herein as to that particular Software component. Your purchase,
acceptance, or use of the Software will constitute your acceptance
of such End-User Licenses.
By purchase, use or acceptance of the Software you further agree
to comply with all export laws and regulations of the United States
as such laws and regulations may exist from time to time.
Reusable Code in This Book
The authors created reusable code in this publication expressly for
reuse for readers. Sybex grants readers permission to reuse for any
purpose the code found in this publication or its accompanying
CD-ROM so long as all of the authors are attributed in any appli-
cation containing the reusable code, and the code itself is never
sold or commercially exploited as a stand-alone product.
The Graphic Workshop and GIF Construction Set software
included with this publication is provided as shareware for your
evaluation. If you try this software and find it useful, you are
requested to register it as discussed in its documentation and in the
applications’ “About” screen. SYBEX has not paid the registration
fee for this shareware.
Software Support
Components of the supplemental Software and any offers associ-
ated with them may be supported by the specific Owner(s) of that
material, but they are not supported by SYBEX. Information
regarding any available support may be obtained from the Owner(s)
using the information provided in the appropriate read.me files or
listed elsewhere on the media.
Should the manufacturer(s) or other Owner(s) cease to offer sup-
port or decline to honor any offer, SYBEX bears no responsibility.
This notice concerning support for the Software is provided for
your information only. SYBEX is not the agent or principal of the
Owner(s), and SYBEX is in no way responsible for providing any
support for the Software, nor is it liable or responsible for any sup-
port provided, or not provided, by the Owner(s).
SYBEX warrants the enclosed media to be free of physical defects
for a period of ninety (90) days after purchase. The Software is not
available from SYBEX in any other form or media than that enclosed
herein or posted to
. If you discover a defect in the
media during this warranty period, you may obtain a replacement
of identical format at no charge by sending the defective media,
postage prepaid, with proof of purchase to:
Product Support Department
1151 Marina Village Parkway
Alameda, CA 94501
After the 90-day period, you can obtain replacement media of
identical format by sending us the defective disk, proof of pur-
chase, and a check or money order for $10, payable to SYBEX.
SYBEX makes no warranty or representation, either expressed or
implied, with respect to the Software or its contents, quality, per-
formance, merchantability, or fitness for a particular purpose. In
no event will SYBEX, its distributors, or dealers be liable to you or
any other party for direct, indirect, special, incidental, consequen-
tial, or other damages arising out of the use of or inability to use
the Software or its contents even if advised of the possibility of
such damage. In the event that the Software includes an online
update feature, SYBEX further disclaims any obligation to provide
this feature for any specific duration other than the initial posting.
The exclusion of implied warranties is not permitted by some
states. Therefore, the above exclusion may not apply to you. This
warranty provides you with specific legal rights; there may be
other rights that you may have that vary from state to state. The
pricing of the book with the Software by SYBEX reflects the allo-
cation of risk and limitations on liability contained in this agree-
ment of Terms and Conditions.
Shareware Distribution
This Software may contain various programs that are distributed
as shareware. Copyright laws apply to both shareware and ordinary
commercial software, and the copyright Owner(s) retains all rights.
If you try a shareware program and continue using it, you are
expected to register it. Individual programs differ on details of trial
periods, registration, and payment. Please observe the require-
ments stated in appropriate files.
Copy Protection
The Software in whole or in part may or may not be copy-protected
or encrypted. However, in all cases, reselling or redistributing
these files without authorization is expressly forbidden except as
specifically provided for by the Owner(s) therein.
4134FM.qxd 8/27/02 11:34 AM Page v
This book is dedicated to my loving wife—
she is my first, best friend.
4134FM.qxd 8/27/02 11:34 AM Page vi
hanks to my wife, Rebecca, for working with me to get this book completed during an
exceptionally difficult time. I really don’t know what I would have done without her help
in researching and compiling some of the information that appears in this book (especially
the glossary). She also did a fine job of proofreading my rough draft and page-proofing the
final result.
Russ Mullen deserves thanks for his technical edit of this book. He greatly added to the
accuracy and depth of the material you see here. I really appreciated the time he devoted to
checking my code for accuracy—especially the last minute checks of test utilities. Russ also
supplied some of the URLs you see in the book and other helpful tips and hints.
Matt Wagner, my agent, deserves credit for helping me get the contract in the first place
and taking care of all the details that most authors don’t really consider. I always appreciate
his help. It’s good to know that someone wants to help.
Finally, I would like to thank Denise Santoro Lincoln, Kylie Johnston, Judy Flynn, Dan
Mummert, Kevin Ly, Lynnzee Elze, William Rodarmor, and the rest of the production staff
at Sybex for their assistance in bringing this book to print. It’s always nice to work with such
a great group of professionals.
4134FM.qxd 8/27/02 11:34 AM Page vii
Introduction xix
Part I An Overview of the Win32 API 1
Chapter 1:Overcoming Holes in the .NET Framework 3
Chapter 2:Working with Win32 API Data 21
Chapter 3:Accessing the Win32 API 45
Chapter 4:Processing Windows Messages 83
Chapter 5:Using Callback Functions 109
Part II Fixing Holes in Standard Applications 131
Chapter 6:Gaining Support for the Console Application 133
Chapter 7:Accessing the Hardware Directly 165
Chapter 8:Overcoming Security Issues 199
Part III Fixing Advanced Win32 API Problems 239
Chapter 9:Accessing Windows XP Special Features 241
Chapter 10:Using Operating System Special Functions 275
Chapter 11:Accessing the Media Player 301
Chapter 12:Working with Microsoft Management Console 335
Part IV Working with DirectX 375
Chapter 13:Creating DirectX Structures and Data Elements 377
Chapter 14:Developing DirectX Access Routines 401
Contents at a Glance
4134FM.qxd 8/27/02 11:34 AM Page viii
Chapter 15:Creating Applications with DirectX 8.1 437
Chapter 16:Extended DirectX Programming Examples 467
Part V Appendices 501
Appendix A:Fifty-Two Tips for Error-Free Win32 API Access 503
Appendix B:Fixes for Common API Access Errors 511
Glossary 519
Index 537
4134FM.qxd 8/27/02 11:34 AM Page ix
Introduction xix
Part I An Overview of the Win32 API 1
Chapter 1 Overcoming Holes in the .NET Framework 3
Why Access the Win32 API? 4
A Case of Missing Functionality 5
Win32 Function Types 7
Win32 Access Requirements 10
Win32 Access for C# Developers 14
Understanding the Effects of Unsafe Code 14
Understanding the Effects of Pointers 16
Advantages for the C# Developer 17
Win32 Access for Visual Basic Developers 18
Understanding Visual Basic Limitations 18
Advantages for the Visual Basic Developer 19
Where Do You Go from Here? 20
Chapter 2 Working with Win32 API Data 21
A Short View of Data 22
Working with Variables 28
Converting Variables to C# Types 29
Converting Variables to Visual Basic Types 30
Special Rules for COM 31
Working with Data Structures 33
Working with Pointers 37
Working with Enumerations 38
Importing Resources 39
Understanding .NET Framework Functionality 40
4134FM.qxd 8/27/02 11:34 AM Page x
Using the IDE Features 41
Working with the Win32 API 42
Where Do You Go from Here? 43
Chapter 3 Accessing the Win32 API 45
An Overview of the DLLs 46
Types of Win32 Access 48
Direct DLL Access 48
C LIB Access 50
A Direct DLL Access Example 52
A C LIB Wrappers Access Example 54
A C LIB Substitute Functions Example 62
Interpreting Error and Result Values 63
Helpful Win32 Programming Tools 66
Dependency Walker 66
Error Lookup 75
Spy++ 76
Where Do You Go from Here? 81
Chapter 4 Processing Windows Messages 83
Understanding the Windows Message Types 84
Windows Message Handlers Found in the .NET Framework 88
An Overview of Windows Message Functions 90
SendMessage() 90
PostMessage(), PostThreadMessage, and PostQuitMessage() 92
SendNotifyMessage() 99
SendMessageCallback() 99
GetMessage() and PeekMessage() 100
RegisterWindowMessage() 101
Creating a Windows Message Handler Example 101
Creating the Event 102
Creating the Windows Message Loop Override 102
Creating the Event Handler 104
Demonstrating the Windows Message Handler 104
Developing for Thread Safety 106
Where Do You Go from Here? 107
4134FM.qxd 8/27/02 11:34 AM Page xi
Chapter 5 Using Callback Functions 109
What Is a Callback Function? 110
Using Callback Functions 111
An Overview of Callback Function Prototypes 112
Implementing a Callback from the Managed Environment 113
Implementing a Callback from a Wrapper DLL 118
Enumerating Calendar Information Example 123
Creating the Macro Wrapper DLL 124
Creating the EnumCalendarInfoEx() Function Code 127
Demonstrating the Calendar Enumeration 128
Where Do You Go from Here? 129
Part II Fixing Holes in Standard Applications 131
Chapter 6 Gaining Support for the Console Application 133
What Does the .NET Framework Provide? 134
Clearing the Screen Example 136
Getting Console Information Examples 139
Working with Code Pages 139
Gaining Access to Console Mode Information 141
Working with Processes 147
Changing the Environment Examples 149
Accessing the Environmental Strings 149
Using Cursors and Fonts 153
Determining the Console Window Title 158
Manipulating the Console Screen Buffer 160
Where Do You Go from Here? 164
Chapter 7 Accessing the Hardware Directly 165
When Is Direct Access Required? 167
Serial Port Access Examples 168
Creating a Serial Stream 169
Determining the Port Status 177
Parallel Port Access Examples 185
Creating the Wrapper DLL 186
4134FM.qxd 8/27/02 11:34 AM Page xii
Viewing the First Level of Printer Information 189
Viewing the Second Level of Printer Information 191
Where Do You Go from Here? 196
Chapter 8 Overcoming Security Issues 199
An Overview of Windows Security 200
A Detailed View of the Windows Security API 202
An Overview of the Functions 209
Using the Access Control Editor 214
Using the Security Configuration Editor 216
Understanding How .NET Role-Based Security Differs 219
Looking Up an Account SID Example 223
Using the GetFileSecurity() Function Example 227
Working with ACEs Example 230
Where Do You Go from Here? 236
Part III Fixing Advanced Win32 API Problems 239
Chapter 9 Accessing Windows XP Special Features 241
What’s New in Windows XP? 242
Common Features 243
Professional Edition Exclusive Features 245
Determining the Operating System Version Example 246
Working with Theme Support Example 253
Balloon Help Example 262
Using NUnit for Automated Testing 268
Where Do You Go from Here? 272
Chapter 10 Using Operating System Special Functions 275
Accessing Status and Other Information 277
Learning How to Avoid Version Compatibility Problems 278
Determining System Power Status Example 281
Creating an Application Shortcut Example 286
Shutting the System Down Remotely Example 290
4134FM.qxd 8/27/02 11:34 AM Page xiii
Obtaining Device Capabilities Example 292
File Compression 295
Using PC-Lint for C++ Development 296
Where Do You Go from Here? 300
Chapter 11 Accessing the Media Player 301
A Quick Overview of the Media Player 302
Windows Media Player General Operation 303
Internet Content 305
Using the Media Library 306
Displaying a Configuration Dialog Example 307
Playing Sound Files Example 313
Determining Device Capabilities 314
Opening a File 317
Playing a File 326
Pausing and Stopping a File 328
Required Application Cleanup 330
Using IconForge 330
Where Do You Go from Here? 334
Chapter 12 Working with Microsoft Management Console 335
Using GUIDGen 337
The Case for an MMC Snap-In 338
Creating a Wrapper DLL 341
Creating an Interface 342
Writing the MMC Wrapper DLL 347
Developing the MMC Snap-In Example 360
Developing an About Dialog 360
Working with IDataObject 363
Creating IComponent and IComponentData 366
Testing the Snap-In within MMC 369
Where Do You Go from Here? 372
4134FM.qxd 8/27/02 11:34 AM Page xiv
Part IV Working with DirectX 375
Chapter 13 Creating DirectX Structures and Data Elements 377
Using the DXDIAG Utility 378
Learning about DirectX Compatibility 380
Viewing the Drivers 383
Working with the DirectX Structures 384
An Overview of the Data Structures 385
Structure Conversion Essentials 388
Understanding DirectX Data Pitfalls in the Managed Environment 397
Where Do You Go from Here? 399
Chapter 14 Developing DirectX Access Routines 401
Working with DirectX Functions 402
DirectDrawCreate() and DirectDrawCreateEx() 403
DirectDrawCreateClipper() 405
DirectDrawEnumerate() and DirectDrawEnumerateEx() 405
Function Declarations 406
Function Return Values 409
Creating DirectX Callback Function Prototypes 412
DDEnumCallback() and DDEnumCallbackEx() 412
EnumModesCallback() and EnumModesCallback2() 413
EnumSurfacesCallback(), EnumSurfacesCallback2(), and
EnumSurfacesCallback7() 413
EnumVideoCallback() 414
Delegate Declarations 414
Working with the DirectX Interfaces and Classes 415
Learning the DirectX Capabilities of the Host Machine Example 416
Using the DirectDrawEnumerateEx() Function 416
Using the DirectX Caps Viewer Tool 419
A Simple 2D DirectDraw Example 424
Importing the DirectX COM Library 424
Writing the Code 425
Using the GIF Construction Set 430
Where Do You Go from Here? 435
4134FM.qxd 8/27/02 11:34 AM Page xv
Chapter 15 Creating Applications with DirectX 8.1 437
An Overview of DirectX 7 and DirectX 8.1 Differences 438
Consolidated Objects 439
Updated Objects and Features 440
An Overview of the Tools 442
Using the DirectX Control Panel Application 442
Using the DMO Test Utility 447
Creating a Test File Using GraphEdit 447
Testing the WavesReverb DMO 449
A Simple DirectSound Example 452
Using the Force Feedback Editor 454
A Simple DirectInput Example 459
Using the DirectX Texture Tool 463
Where Do You Go from Here? 465
Chapter 16 Extended DirectX Programming Examples 467
Using the GraphEdit Utility 468
Creating a Connection 469
Working with Multiple Streams 470
Working with Filters 472
Performance Tuning 474
Saving the Result 476
Using the DirectPlay Network Simulator 477
Using the MeshView Tool 479
Creating a Mesh 480
Adding Color 482
Making Other Changes 485
Using a Mesh Example 489
Initializing the Application 489
Loading a Mesh File 491
Displaying the Image On Screen 494
A Few Words about Output 498
Where Do You Go from Here? 500
4134FM.qxd 8/27/02 11:34 AM Page xvi
Part V Appendices 501
Appendix A Fifty-Two Tips for Error-Free Win32 API Access 503
Appendix B Fixes for Common API Access Errors 511
Resolving Data Corruption in Data Structures 512
The [DllImport] Attribute Works Improperly 513
Data Transfer Problems 514
.NET Implementation of COM Interface Doesn’t Work 516
Handling Memory Leaks and Other Resource Problems 517
Windows Doesn’t Appear to Handle Messages Correctly 518
Glossary 519
Index 537
4134FM.qxd 8/27/02 11:34 AM Page xvii
4134FM.qxd 8/27/02 11:34 AM Page xviii
ey! I needed that!
You might be tempted to yell something like this when you discover that Microsoft has
implemented some, but not all, of the Win32 API in the .NET Framework. In some cases,
you might find that Microsoft mislaid the feature in an out-of-the-way spot, but more often
than not, the feature is simply missing. It’s not documented anywhere and Microsoft doesn’t
give you even one clue as to where the feature might have gone. A visit to the newsgroups
will often yield a pathetic claim that the missing feature will appear in the next version of the
.NET Framework—so much for developing your application today.
The good news is that there are ways around your problem. In fact, sometimes the method
for overcoming the loss of a feature is so simple you have to wonder why Microsoft didn’t
implement it (or at least document it). In other situations, the road to your missing Win32
function lies along a twisted path strewn with the boulders of incompatibility. This book helps
you in both cases. We explore both the easy and the hard fixes. In fact, by the time you com-
plete this book, you’ll have discovered that the .NET Framework simply hides much of the
functionality that you thought it offered as an open feature.
Hunting for Treasure
In some respects, this book is about the adventure of programming in the .NET Framework.
Like any adventure, you need a map to find the treasure at the end, and this book is your map.
You’ll discover all of the functionality that other developers only dream about listed right in
this map, and not only that, the road is marked for easy recovery. I’ll also show you all of the
hidden traps and how to avoid them. We’ll discuss the problems of implementing an applica-
tion solution that relies on the Win32 API and how you can easily achieve success.
We’ll begin simply by looking at the tools you need to go on your adventure. You’ll learn
about messaging and using callback functions. Together we’ll explore the depths of the data
structure. In many places, you’ll learn about the secret code words required to open the doors
of files filled with treasure. For many of you, the path will begin to look familiar. But watch out!
Working with the Win32 API from .NET is nothing like working with it from the languages
of days gone by.
4134FM.qxd 8/27/02 11:34 AM Page xix
Once you’re an accomplished adventurer, we’ll begin delving into the new features found in
Windows XP. You’ll begin to understand that you don’t have to implement security Microsoft’s
way and that the hardware really hasn’t disappeared after all. Adventurers with a thirst for the
most exotic treasures will discover the media player, MMC snap-ins, and even DirectX. By
the time the journey ends, you’ll find that every dream of Windows functionality treasure you
might have wanted is answered. In sum, this is the one true map for all .NET developers who
need the Win32 API in all of its forms.
Hidden Nuggets
This book is also about finding the hidden nuggets that all adventurers seek. In many of the
chapters, you’ll learn about tools that you might not have known about and will almost certainly
learn new ways to use them. We’ll also discuss how to create tools of your own. Finally, you’ll
receive two special DLLs that will help you overcome the problems of Win32 API access. The
first DLL helps you create MMC snap-ins with less effort. The second DLL does the same for
Who Should Read This Book?
I’ve designed this book for Visual Basic .NET and Visual C# .NET developers who need access
to the Win32 API. Given the current state of the .NET Framework, I’m betting that most
.NET developers will need some type of access to the Win32 API, and this book explores the
issue at all levels. All of the examples contain full explanations, and for each, you’ll find both
the source and the compiled example on the CD that accompanies this book.
You won’t find any information on using the language of your choice in this book—I con-
centrate on the Win32 API and what you need to work with it. Consequently, you won’t want
to look at this book until you’ve already learned to use either Visual Basic or Visual C#. We’ll
begin working with the Win32 API in the examples that appear in the first chapter and you
won’t stop until you reach the end of the book. Every chapter has at least one detailed example,
and most contain several. You’ll also find supplementary examples in the
folder of
the CD.
Tools Required
There are some assumptions that I’ve made while writing the application programming
examples in this book. While writing this book, I used a Windows 2000 and Windows XP
workstation. There’s no guarantee that any of the code in the book will work with Windows 9x,
although most of it will. You must install the latest service packs for all products before the
examples will work properly. Microsoft’s .NET product line is new technology and relies on
4134FM.qxd 8/27/02 11:34 AM Page xx
the latest versions of many DLLs and the .NET Framework. In some cases, I’ll list other
special requirements that you must observe before the example application will run.
Most of the concepts you’ll learn in this book won’t appear in your online documentation.
Some of it’s so new that it only appears on selected Web sites. Throughout the book
you’ll find tips and notes alerting you to the location of such information. In addition,
Microsoft made some material available only through selected channels like an MSDN
subscription. Other pieces of information are simply undocumented,and you won’t find
them anywhere except within a newsgroup when someone finds the feature accidentally.
In a few cases,I’ll tell you outright that I learned about the feature through trial and
error—the type of research you won’t have to perform when using this book.
I tested all of the examples in this book with Visual Studio .NET Enterprise Architect
Edition. None of these examples are guaranteed to work with any other programming
language products and none of them will work with the educational versions of Visual Studio.
Conventions Used in This Book
It always helps to know what the special text means in a book. In this section we’ll cover
usage conventions. This book uses the following conventions:
Convention Explanation
Inline Code
Some code will appear in the text of the book to help explain application function-
ality. The code appears in a special font that makes it easy to see it. This mono-
spaced font also makes the code easier to read.
Inline Variable
As with source code,variables that appear inline will also appear in a special font
that makes them stand out from the rest of the text. When you see monospaced
text in an italic typeface,you can be sure it’s a variable of some type.
User Input
Sometimes I’ll ask you to type something. For example,you might need to type a
particular value into the field of a dialog box. This special font helps you see what
you need to type.
] When you see square brackets around a value,switch,or command,it means
that this is an optional component. You don’t have to include it as part of the
command line or dialog field unless you want the additional functionality that the
value,switch,or command provides.
A variable name is a value that you need to replace with something else. For
example,you might need to provide the name of your server as part of a command-
line argument. Because I don’t know the name of your server,I’ll provide a variable
name instead. The variable name you’ll see usually provides a clue as to what kind
of information you need to supply. In this case,you’ll need to provide a filename.
Continued on next page
4134FM.qxd 8/27/02 11:34 AM Page xxi
Convention Explanation

Open Menus and the selections on them appear with a special menu arrow symbol.

Open” means “Access the File menu and choose Open.”
italic You’ll normally see words in italic if they have special meaning or if this is the first
use of the term and it is accompanied by a definition. Always pay special atten-
tion to words in italic because they’re unique in some way.
Some words appear in a monospace font because they’re easier to see or require
emphasis of some type. For example,all filenames in the book appear in a mono-
space font to make them easier to read.
URLs will normally appear in a monospace font so that you can see them with
greater ease. The URLs in this book provide sources of additional information
designed to make your development experience better. URLs often provide
sources of interesting information as well.
This book contains many icons that help you identify certain types of information. The
following paragraphs describe the purpose of each icon.
Notes tell you about interesting facts that don’t necessarily affect your ability to use the
other information in the book. I use note boxes to give you bits of information that I’ve
picked up while using C#,Windows 9x,Windows 2000,or Windows XP.
Everyone likes tips because they tell you ways of doing things that you might not have
thought about before. Tip boxes might also provide an alternative way of doing some-
thing; often you might like the alternative better than the first approach I provided.
You’ll also find that I use notes and tips to hold amplifying information. For example,
many of the URLs in this book appear as part of a note or a tip. The Internet contains a
wealth of information, but finding it can be difficult, to say the least. URLs within notes and
tips help you find new sources of information on the Internet, information that you can use
to improve your programming or learn new techniques. You’ll also find newsgroup URLs
that tell where you can find other people to talk with about C#. Finally, URLs will help you
find utility programs that’ll make programming faster and easier than before.
The warning icon means “Watch out!” Warnings almost always tell you about some kind of
system or data damage that’ll occur if you perform a certain action (or fail to perform
others). Make sure you understand a warning thoroughly before you follow any instructions
that come after it.
4134FM.qxd 8/27/02 11:34 AM Page xxii
About the Author
John Mueller is a freelance author and technical editor. He has writing in his blood, having
produced 55 books and over 200 articles to date. The topics range from networking to artificial
intelligence and from database management to heads-down programming. Some of his current
books include a C# developer guide, a small business and home office networking guide, and
several Windows XP user guides. His technical editing skills have helped over 29 authors refine
the content of their manuscripts. John has provided technical editing services to both Data
Based Advisor and Coast Compute magazines. He’s also contributed articles to magazines like
SQL Server Professional, Visual C++ Developer, and Visual Basic Developer. He’s currently the
editor of the .NET electronic newsletter for Pinnacle Publishing.
When John isn’t working at the computer, you can find him in his workshop. He’s an avid
woodworker and candle maker. On any given afternoon, you can find him working at a lathe
or putting the finishing touches on a bookcase. One of his newest craft projects is glycerin
soap making, which comes in handy for gift baskets. You can reach John on the Internet at
. John is also setting up a Web site at
. Feel
free to look and make suggestions on how he can improve it. One of his current projects is creat-
ing book FAQ sheets that should help you find the book information you need much faster.
4134FM.qxd 8/27/02 11:34 AM Page xxiii
4134FM.qxd 8/27/02 11:34 AM Page xxiv
Part I
An Overview of the
Win32 API
Chapter 1:Overcoming Holes in the .NET Framework
Chapter 2:Working with Win32 API Data
Chapter 3:Accessing the Win32 API
Chapter 4:Processing Windows Messages
Chapter 5:Using Callback
4134c01.qxd 8/26/02 11:46 AM Page 1
4134c01.qxd 8/26/02 11:46 AM Page 2
Overcoming Holes in the
.NET Framework

Why Access the Win32 API?

Win32 Access for C# Developers

Win32 Access for Visual Basic Developers
Chapter 1
4134c01.qxd 8/26/02 11:46 AM Page 3
here are few, if any, perfect programming platforms in the world and .NET is no exception.
Developers who spend any time working in the unmanaged environment before they begin
working with .NET will notice some distinct problems with functionality in the .NET envi-
ronment. Some of these holes (such as those in the security area) are apparent and require an
immediate fix; others (such as the lack of support for a
function) are subtle and you
might never notice them. The point is that the.NET Framework is new technology and there
are bound to be some holes in coverage, and you’ll notice them with regular frequency.
This chapter provides a quick overview of some major areas of omission in the .NET
Framework. I want to say at the outset that I feel the .NET Framework is a big improvement
over using unmanaged code, but it’s new and lacks some features that most developers will
need. Consequently, you’ll find that this book discusses “holes” in coverage or augmentation
of features. I’m not here to tell you that the .NET Framework is technically flawed. The goal
of this chapter is to help you plan your development efforts to make the best use of existing
.NET Framework functionality and to access the Win32 API when the .NET Framework
proves less than perfect.
Visual C++ represents a unique language in .NET because it provides both managed and
unmanaged coding environments. Consequently,you can access the Win32 API in its
entirety from Visual C++ using the same unmanaged techniques you used before .NET
appeared on the horizon. This unique functionality means that Visual C++ developers
won’t need the special techniques found in this book. It also means that you can use
Visual C++ as a language bridge between managed and unmanaged environments.
Why Access the Win32 API?
Many of you have a lot of experience working with the Win32 API are already familiar with
the programming requirements for unmanaged code. The idea of working with unmanaged
code presents few problems for the seasoned developer. However, the .NET Framework that
Microsoft has advertised is supposed to obviate the need to work with unmanaged code, so the
first question on most developer’s minds is: why they would even need to access the Win32
API? The short answer is that you’ll find a lack of functionality in some areas such as DirectX,
the Microsoft Management Console (MMC), and direct hardware access when working with the
.NET Framework. You can only gain access to this functionality through the Win32 API.
The long answer requires a little more explanation. For example, not all .NET languages
have an equal measure of missing functionality. The .NET Framework doesn’t include a
function, so you’ll find this feature missing in C# as well. However, because Visual Basic includes
function as part of the language, it doesn’t require any special programming to access
Chapter 1 • Overcoming Holes in the .NET Framework
4134c01.qxd 8/26/02 11:46 AM Page 4