Main Index Screen
Microsoft Visual C++ for Windows NT and Windows Samples

Source Code Examples

  Building the Samples

  Alphabetical List of Samples

  Cross-Reference to Samples by Subject

  Disclaimer


Alphabetical List of Samples

Sample	Illustration
Angle		GDI Arc Demonstration
Bounce		Writing Multithread Applications Sample Code
BPointer		Based Pointer Demonstration
BSort		Source Profiler Sample Code
Check_SD		Security Descriptor Demonstration
Client		Dynamic Data Exchange Manager Library (DDEML) Example
ClipText		Clipboard Demonstration
Clock		Dynamic Data Exchange Manager Library (DDEML) Example
CmnDlg		Common Dialog Box Demonstration
Comm		Communications API Function Demonstration
Console		Demonstration of the Console API Functions
ConsoleC		Setting Console Attributes
ConGUI		Console I/O combined with GUI I/O
Cursor		Cursor Demonstration
CvtMake		Visual C++ Internal Makefile Conversion Utility
DDEInst		Dynamic Data Exchange Manager Library (DDEML) Example
DDEML		Dynamic Data Exchange Manager Library (DDEML) Example
DDEMO		Dynamic Data Exchange Manager Library (DDEML) Example
DEB		Debug Event Browser
DlgEdit		Dialog Editor Source Code
Drives		Drive and File System Information Demonstration
Event		Asynchronous I/O API Function Demonstration
ExitWin		System Logoff Demonstration
Filer		File I/O API Function Demonstration
FontView		Font Usage Utility
Floppy		Direct Floppy-Disk Access Demonstration
GDIDemo		GDI Sample Application
Generic		Sample Template Windows Program
GetDev		Get Device Capabilities Demonstration
GetSys		Get System Information Demonstration
GridFont		Unicode Font Selection Demonstration
Hooks		Demonstration of Monitoring System Events
Inherit		Redirection of Standard I/O
Input		Keyboard and Mouse Input Monitoring
Locale		International Locale Demonstration
MaskBlt		GDI Masked Bit Copy Demonstration
MDI_		Multiple Document Inferface Demonstration
Memory		Interprocess Memory Sharing
Menu		Menu Demonstration
MltiThrd		Multiple Thread Example
Monkey		Using API Functions to Access the Registry
MultiPad		Multiple Document Interface (MDI) Example
MyPal		Palette Management Example
NPClient		Named Pipe Client/Server Demonstration
NPServer		Named Pipe Client/Server Demonstration
OthrProc		Shared Memory Demonstration
Output		Simple GDI Graphics Demonstration
OwnCombo		Owner-Draw Combo Box Demonstration
Paths		GDI Paths API Demonstration
Platform		Windows Platform Detection Demonstration
PlgBlt		GDI PlgBlt API Demonstration
PolyDraw		GDI PolyDraw API Demonstration
PortTool		Win32 Porting Tool Source Code
Printer		Printing Demonstration
Process		Creating and Terminating Processes
Profiler		Source Profiler Sample Code
PView		Process Viewer Source Code
ReadWrit		Read/Write Synchronization Demonstration
Regions		GDI Regions API Demonstration
Registry		Using API Functions to Access the Registry
Select		Simple DLL Demonstration
SetInfo		File Information Demonstration
Service		Services Demonstration
ShareMem		Shared Memory Demonstration
ShowDib		Opening and Displaying Device Independent Bitmaps (DIBs)
SidCln		Demonstration of the Win32 Security API Functions
SimplDLL		Simple DLL Demonstration
Simple		Minimum Console Application
SortForm		DLL Import and Export Demonstration
Spy		Message Viewer Source Code
StartP		Process Priority Demonstration
StreBlt		GDI StretchBlt API Demonstration
Subclass		Control Subclassing Demonstration
TakeOwn		Administrator Security Demonstration
TermProc		Process Termination Demonstration
Threads		Thread Demonstration
Timers		Demonstration of the Windows Timing API
TLS		Demonstration of the Windows Timing API
TTFONTS		Font Display Demonstration
UniPut		Demonstration of the Windows Timing API
UThunk		Win32s Universal Thunk Demonstration
VirtMem		Demonstration of the Windows Timing API
Walk		Directory API Demonstration
WinDiff		Graphical Difference Marker Source Code
World		Metafile World Coordinate Transformation Demonstration
WSock		Demonstration of the Windows Sockets API
WXForm		World Coordinate Transformation Demonstration


Cross-Reference to Samples by Subject

Simple Applications

Simple	Generic	Select	SimplDLL
User Interface

Console	Congui	Console	ConsoleC	Inherit
Window and Control Related	ClipText	CmnDlg	Cursor	Input
	MDI_	Menu	MultiPad	OwnCombo
	Subclass
Graphics (GDI)	Angle	GetDev	GDIDemo	MyPal
	Output	Paths	PolyDraw	Printer
	Regions	World	WxForm
Bitmaps	MaskBlt	PlgBlt	ShowDib	Streblt
Fonts	Fontview	GridFont	TTFONTS
Interprocess Communication

Dynamic Data Exchange Application Suite	Client	Clock	DDEInst
	DDEMO	Server
Named Pipes	NPClient	NPServer
Shared Memory	BPointer	Memory	OthrProc
	ShareMem
Sockets	WSock
File System related

Drives	Event	Filer	Floppy	SetInfo

Walk

Security

Check_SD	ExitWin	Registry	Service	SidCln

Takeown

Processes and Threads

Bounce	Hooks	MltiThrd	Process	ReadWrit
StartP	TermProc	Threads	TLS
Tool Source

CvtMake	DlgEdit	PortTool	PView	Spy

WinDiff

Miscellaneous

BSort	Comm	DEB	GetSys	Locale
Platform	SortForm	Timers	UniPut	UThunk

VirtMem


Disclaimer
Microsoft Visual C++ for Windows NT comes with a number of sample programs that are intended to illustrate various aspects of the system. These sample applications should be used as a simple reference and starting point only. They should not be considered to represent the only, or even best way to achieve similar functionality in your own applications.


Building the Visual C++ Samples
Building the Samples

You can build most of the Microsoft Foundation Class Library samples in either of two ways::

Build the samples from the Visual C++ Workbench; or

Build the samples from the command line.

To build a sample from the Visual C++ Workbench, use the Project Open command, change the directory to that of the sample, and select the sample's .MAK file. If during the installation of Visual C++ you chose the default directories, the sample directory will be a subdirectory of \MSVCNT\SAMPLES.

You can build a sample from the command line by running NMAKE, using either the Visual C++ .MAK file for the sample or a makefile with the default MAKEFILE name. If you use the .MAK file, then you must specify with the NMAKE /f option, as in:

nmake /f hello.mak

To obtain the additional versions of the C Run-time libraries, if you have not already installed them, requires that you run the Visual C++ setup program again to select these versions.  Note, you can do this without having to reinstall the rest of Visual C++.

We encourage you to use the source browsing capability of Visual C++ with the samples. To create a browser database for a sample, follow these steps:

1.	Select the Options command from the Workbench.

2.	Choose Compiler from Customize Build Options in the Project Options dialog.

3.	Choose Listing Files from the Category in the C/C++ Compiler Options.

4.	Chose Browser Information from Category Settings for Listing Files.

For more details, see the Visual Workbench User's Guide.


Copyright Notice
Copyright Notice for Visual C++ Sample Programs Help

Information in this document is subject to change without notice. Companies, names, and data used in examples herein are fictitious unless otherwise noted. No part of this document may be reproduced or transmitted in any form or by any means, electronic or mechanical, for any purpose, without express written permission of Microsoft Corporation.

© 1993 Microsoft Corporation. All rights reserved.

Microsoft is a registered trademark and Windows and Windows NT are trademarks of Microsoft Corporation.


  Angle

GDI Arc Demonstration

Location

\MSVCNT\SAMPLES\ANGLE

Summary

The sample named ANGLE provides a demonstration of how the AngleArc() API function works. The X, Y, and RADIUS parameters are all in the world coordinate space. The start angle and sweep angle are floating-point values and are interpreted as degrees.

More Information

This program presents a dialog box stretched across the top of the window. The user can set the parameters for the AngleArc() API function by changing the values in the entry fields of this dialog box. A button on the dialog box then allows the user to immediately see the results of these values on the arc in the client area. If the values in the entry field are invalid, the program will write out this information and not draw the arc. The origin of the viewport is shifted down in the client area so that it exists at the upper-left corner of the viewable area.


  Bounce

Writing Multithread Applications Sample Code

Location

\MSVCNT\SAMPLES\BOUNCE

Summary

The BOUNCE sample is designed to be used with the chapter on writing multithread applications in the Programming Techniques book. See this documentation for more information.


  BPointer

Based Pointer Demonstration

Location

\MSVCNT\SAMPLES\BPOINTER

Summary

When several processes need to access shared data, there is no guarantee that the shared memory is mapped to the same locations in all processes. This can cause a problem when the data contains relative pointers because a pointer value that is valid in one process's context may not be valid in the context of the other processes.

This sample demonstrates the use of based pointers to allow manipulation of shared data from several processes using memory mapped files. This technique is applicable to all forms of shared memory.

More Information

The sample contains the following modules:

CHGDATA.EXE

A console process that lets you add elements to a shared  linked list.

READDATA.EXE

A console process that allows you to view the shared data that is created by CHGDATA. It dereferences pointers as it encounters them.

Note, however, that based pointers reduce the performance of the application using the pointers because the pointers must be resolved at run time; that is, each access typically adds one machine instruction overhead when dereferencing a pointer.

Once the files are compiled, execute CHGDATA.EXE and follow the instructions it displays. Start READDATA.EXE while running CHGDATA.EXE to read the data entered.


  BSort

Source Profiler Sample Code

Location

\MSVCNT\SAMPLES\BSORT

Summary

The BSORT sample is designed to be used with the documentation for the Microsoft Source Profiler. See your Profiler documentation for more information.


  Check_SD

Security Descriptor Demonstration

Location

\MSVCNT\SAMPLES\CHECK_SD

Summary

The CHECK_SD sample program explores the default security descriptors (SDs) that Windows NT places on objects. This sample examines the SD on files and can be modified to examine the SD on other objects.

More Information

  To run the sample

1.	Type Check_sd to check the SD on the \\.\A: device.

2.	Type Check_sd d:\a.fil to check the SD on the d:\a.fil file. In this case, d: must be formatted NTFS because only NTFS files have SDs.

You can access the comment describe above by doing the following in the Win32 .HLP file:

1.	Click Functions and Overviews.

2.	Choose the "Security" set of functions.

3.	From the display of the list of security functions, click the Overview button.

4.	Choose the subtopic "Allowing Access" from the list of topics under Security Overview.


   ClipText

Clipboard Demonstration

Location

\MSVCNT\SAMPLES\CLIPTEXT

Summary

This program demonstrates the use of the Edit menu to copy and paste text to and from the clipboard. Try using the Copy command to move this text to the clipboard, and the Paste command to replace this text with data from another application. You might want to try running Notepad and Clipbrd alongside this application so that you can watch the data exchanges take place.


   CmnDlg

Common Dialog Box Demonstration

Location

\MSVCNT\SAMPLES\CMNDLG

Summary

CMNDLG is a sample demonstrating the use of all of the common dialog box functions in the Win32 API .

More Information

Each dialog box is demonstrated being used in three different ways: standard, using a hook function, and using a modified dialog template.


  Comm

Communications API Function Demonstration

Location

\MSVCNT\SAMPLES\COMM

Summary

The COMM sample application is designed to demonstrate the basics of using the Win32 communications API functions while maintaining a common code base with Win16 code.

More Information

The TTY.EXE program performs communications using the Windows functions OpenFile, ReadFile, SetCommState, SetCommMask, WaitCommEvent, WriteFile and CloseFile.

This sample creates a background thread to watch for COMM receiver events and posts a notification message to the main terminal window. Foreground character processing is written to the communications port.

Simple TTY character translation is performed and a screen buffer is implemented for use as the I/O window.

Overlapped file I/O techniques are demonstrated.

To Use

The baud rate, data bits, stop bits, parity, port, RTS/CTS handshaking, DTR/DSR handshaking, and XON/XOFF handshaking can be changed under the Settings menu item.

Once the communications settings are setup, the Action menu item can be selected to connect or disconnect the TTY program.


   Console

Demonstration of the Console API Functions

Location

\MSVCNT\SAMPLES\CONSOLE

Summary

The CONSOLE sample demonstrates most of the Win32 console API functions. The program takes no parameters; to start, just run CONSOLE.EXE. After starting the sample, you can click on one of the functions on the screen to get a demonstration of that function. When viewing a demo of the function, the title of the console window is changed to show the name of the source file where that demo function resides. This should make it easy to find the sample code where the function of interest resides.


   ConsoleC

Setting Console Attributes

Location

\MSVCNT\SAMPLES\CONSOLEC

Summary

The CONSOLEC sample illustrates the use of the SetConsoleTextAttribute() and GetConsoleScreenBufferInfo() functions to set the console text color attributes.

More Information

This sample also functions as a utility to set the text color of the console window. The command syntax for the utility is as follows:

COLOR FOREGROUND [BACKGROUND]

FOREGROUND and BACKGROUND are the new text color selections for the current console. If the utility is invoked without any options, the utilities syntax and a table of the possible color choices is displayed. The BACKGROUND selection is optional, and thus just the FOREGROUND text color can be changed.

Possible colors are: black, blue, green, cyan, red, magenta, yellow and white. Each of these can be selected as the FOREGROUND or the BACKGROUND color. Selection of the same color for both the FOREGROUND and the BACKGROUND is not permitted. The color options are not case sensitive, and only the first unique characters are necessary to select the color. For example

COLOR BLU W

will select blue on white text color attributes.

The text color attribute changes only affect new console output. Thus, text in the console buffer before the utility is invoked retains its original color attributes.


   ConGUI

Console I/O combined with GUI I/O

Location

\MSVCNT\SAMPLES\CONGUI

Summary

ConGUIis a simple example of how a standard 'console' application might also take advantage of some of the graphical capabilities of Windows NT.

More Information

There are many applications that for one reason or another would have nothing to gain by implementing full fledged 'GUI' interface with Title Bars, Menus, Scrollable Client Area etc. But that doesn't mean they have to be stuck in the world of characters forever.

Take the example of a compiler for instance. Without an IDE, a compiler has no need for menus, button bars, or many of the other UI aspects of a standard Windows application.

The user of a compiler simply wants to launch the compiler with special command line switches, and let it do its thing, then return control back to the user. In this scenario however, there is a timer where the user might want the compiler to be 'friendlier' then what the current generation of compiler is. Do you know what all the command line switches are for your compiler? Do you occasionally want some on-line assistance with understanding what the compiler is capable of?

ConGUI illustrates the usage of a '/dialog' parameter, which will bring up a fully functional dialog box that will assist the user in selecting the parameters that they want for the command line.

Want to see a little more information about some of those switches? Then allow the user to access a full featured WinHelp file like other 'GUI' applications have. ConGUI shows how it is extremely easy for a console application to make standard WinHelp calls to access the graphical help engine.

Another feature that ConGUI shows, is how it is possible for a console application to figure out how it was launched. It would often be useful for a text application to realize that it was being launched into its own window, and that when it closed down, the window it had written all of its output into would be closed down as well. Windows NT doesn't currently provide an easy mechanism for doing this, but by making a couple of calls to determine some of the window states, an application can do a pretty good job at figuring this out.

To see this in action, try the following methods of executing ConGUI, and notice how it behaves:

1.	Double-click the .EXE from the File Manager.

2.	Add it to a group in the Program Manager, and double-click it from there.

3.	From a command prompt, type :

CONGUI

4.	From a command prompt, type :

START CONGUI

5.	From a command prompt, type :

CONGUI > TEMP.TXT

This sample application is not necessarily intended to demonstrate 'the' way that console applications should be written for Windows NT, it is merely demonstrating a possible way you could add some additional features to your application to make it more useful to your users, and hopefully stand out from some of your competition.


   Cursor

Cursor Demonstration

Location

\MSVCNT\SAMPLES\CURSOR

Summary

CURSOR illustrates how to use the mouse pointer to highlight a graphical region. It also demonstrates how to change the mouse cursor to reflect program status.

More Information

Click the left mouse button and drag to select a region. Press ENTER to change the cursor shape while performing a calculation.


   CvtMake

Visual C++ Internal Makefile Conversion Utility

Location

\MSVCNT\SAMPLES\CVTMAKE

Summary

CVTMAKE converts internal makefiles from the 16-bit version of Visual C++ to 32 bits and vice-versa. This conversion is performed through string substitution and copying.

More Information

This utility can be useful for migrating 16-bit projects to 32 bits. The files 16TO32.DEF and 32TO16.DEF contain the string substitutions used in the conversions, and can be modified using a standard text editor.

CVTMAKE is described in more detail in the CVTMAKE.WRI file included in the \MSVCNT\SAMPLES\CVTMAKE directory.


            DDEML

Dynamic Data Exchange Manager Library (DDEML) Example

Location

\MSVCNT\SAMPLES\DDEML\CLIENT

\MSVCNT\SAMPLES\DDEML\CLOCK

\MSVCNT\SAMPLES\DDEML\DDEINST (Not compatible with Win32s)

\MSVCNT\SAMPLES\DDEML\DDEMO

\MSVCNT\SAMPLES\DDEML\SERVER

Summary

SERVER.EXE, CLIENT.EXE, CLOCK.EXE, and DDEINST.EXE are part of a DDEML example application.


  DEB

Debug Event Browser

Location

\MSVCNT\SAMPLES\DEB

Summary

The Debug Event Browser (DEB) sample demonstrates the Win32 Debug API. This sample acts as a debugger for both newly created debuggee processes or attaches to current active processes.

DEB is not a debugger in the traditional sense; it is a browser as its name implies. DEB displays the debug events, and their relevant properties, as they occur and invokes the default handlers supplied either by the debuggee or the system. Only the minimal debug event handling is imposed such that the debug events are displayed and the debuggee is continued on its normal course of execution.


  DlgEdit

Dialog Editor Source Code

Location

\MSVCNT\SAMPLES\SDKTOOLS\DLGEDIT

Summary

The DLGEDIT tool allows you to design and test a dialog box on a display screen instead of defining dialog statements in a resource script. You can use DlgEdit to create new dialog boxes and to add or remove controls from an existing dialog box.  You can then compile this resource file using the resource compiler. The binary output from the resource compiler can then be linked into your application's executable file.

More Information

DlgEdit demonstrates the following techniques:

1.	Creating dialog boxes.

2.	Reading and writing resource files.

3.	Creating control windows.

4.	Creating a help file.

5.	Creating custom controls.

6.	Creating groups of controls.

7.	Working with include files.


  Drives

Drive and File System Information Demonstration

Location

\MSVCNT\SAMPLES\DRIVES

Summary

DRIVES is a demonstration of how the GetDriveType() and GetVolumeInformation() functions determine all logical drives on a system, their disk type (local, remote, CD-ROM, and so on), and their file system type (FAT, HPFS, and so on).

More Information

The additional API functions, GetLogicalDrives() and GetLogicalDriveStrings(), are not required to determine the drive and file system type, but are included as an example of how these API functions can enhance the efficiency of disk querying API calls.

When a drive type is removable (for example, a floppy disk drive), then additional precautions are taken before accessing this drive. A validation check is made to see if media exists in the drive before proceeding. A simple test of opening any file in the root directory of the removable media drive using the OpenFile() API function determines the media's presence. If the OpenFile() call returns a handle, then media is present and further disk querying calls are safely made on the logical drive. If the OpenFile() call fails, then no media is present and no further attempts to query this drive are allowed. Note, in order to eliminate an unwanted pop-up, prompting the user to insert a disk in the drive, from being generated by the operating system, the error mode is temporarily adjusted, using SetErrorMode(), to allow any OpenFile() errors to immediately return to the calling routine.


  Event

Asynchronous I/O API Function Demonstration

Location

\MSVCNT\SAMPLES\EVENT

Summary

The EVENT sample demonstrates performing asynchronous I/O in Win32. In Win32 you can do this in two ways. One way is similar to OS/2 where a thread is spawned that performs the I/O and returns. With Win32, when you create a file, it signals to the system that you want to perform I/O asynchronously. Then, when ReadFile(), for example, is going to take a significant amount of time to complete, an ERROR_IO_PENDING error is generated, signaling you to do other tasks until you NEED the data, at which time you can use the GetOverlappedResults() function, which will finish the I/O.

More Information

Note that this activity has taken place without the need of an additional thread to perform the work. This sample touches only on the capabilities of what one can do with overlapped I/O functions. For example, an application that uses pipes to communicate over the network to other clients can create these file handles with the overlapped flag. Then, instead of blocking and waiting for a connection, the server application can go about doing useful tasks waiting for the pipe to enter the "signaled" state. In addition, you can perform more than one operation on this handle at one time, such as reading and writing to the same file.

All this power does not come without some responsibilities on the programmer's side. First, the system does not keep track of the system file pointers. In addition, you cannot use the data until the system responds by setting an event to a signaled state.

In the first case this just means you need to keep track of the value "lpNumberOfBytesTransfered" returned by GetOverlappedResult() and update the OVERLAPPED structure with this information. This OVERLAPPED structure will then be passed into the Read/WriteFile() function, which will use this as the offset to the starting point for the I/O operation. The first call to Read/WriteFile() will normally then have the offset fields in the OVERLAPPED structure set to zero.

The second case should be used as a criteria of whether to use this type of I/O. If you need the data before you can do anything else, use normal synchronous I/O and let the system handle the details for you. This also demonstrates an important reason for using an EVENT to wait on rather than the file handle. While both are allowed in a multithread application, one cannot guarantee that the thread that set the handle to the signaled state will be the one returning from the GetOverlappedResult() because each thread is using the same handle to wait on.

To keep this sample focused, the user interface is simple. To run this sample at the command prompt, type:

ASYNC_IO <In_file> <Out_file>

In_file and Out_file are place holders. As this is implemented, you cannot write over an existing file. While this is up and running, you will see vital statistics such as, such as the following:

When I/O is pending

How many bytes are transferred

End of file


  ExitWin

System Logoff Demonstration

Location

\MSVCNT\SAMPLES\EXITWIN

Summary

The EXITWIN sample demonstrates the steps necessary to reboot or shut down the machine in Windows NT and Win32s/MS-DOS programmatically. A similar method can be used to log off a user. The steps are as follows:

1.	Check to see if the machine is running Windows NT; if so:

a.	Get the security token.

b.	Fetch the LUID for the SeShutdownPrivilege. This is required only for rebooting and shutting down the machine.

c.	Enable the shutdown privilege.

2.	Use ExitWindowsEx() to log off, shut down or reboot the machine.

More Information

CAUTION: Use this API (application programming interface) with care and with plenty of warning so that a user is not rudely surprised.

There are two methods to prevent the system from shutting down, one at the application level and one at the system level. At the application level, process the WM_QUERYENDSESSION message so the application can ask the user whether he or she wants to save any data that has not been backed up to disk. Then, return TRUE assuming the process can shut down safely or FALSE if it cannot (this will not keep the machine from rebooting or shutting down if the parameter to ExitWindowsEx() was OR'ed with EXW_FORCE). At the system level, it is possible to remove the rights of certain users/groups to reboot the machine. This is done via the User Manager application.


  Filer

File I/O API Function Demonstration

Location

\MSVCNT\SAMPLES\FILER

Summary

FILER is a basic file management applet, similar to the File Manager. It demonstrates many of the File I/O API, and their related algorithms, such as drive enumeration .EXE Version Information retrieval and directory tree walking. It also demonstrates many intensive user algorithms, such as child management, subclassing, synchronization and control window management.

More Information

Filer presents the user with two fixed child windows, each of which the user may associate with a drive from the drives available on the system.

A Drive Toolbar describes the available drives on the system. Users select drives from the toolbar or the Drives menu. A function toolbar also corresponds to the file I/O functions in the File menu.

Each of these Drive child windows contains a Directory ListBox, and a File ListBox, with which the user may browse through the files on the selected drive.

Filer gives the user the option to Open (execute/edit), Copy, Delete, Move, and Rename files, as well as Make and Remove Directories, and display version information embedded in Win32 files. The active Drive child acts as the source, and the inactive Drive child acts as the default destination of file I/O operations.

The Drive children may also be configured as side by side or above and below one another, and the File and Directory Listboxes in each may swap positions.

All features of Filer may be selected from the Mouse, Keyboard, or by Menu Items.


  Floppy

Direct Floppy-Disk Access Demonstration

Location

\MSVCNT\SAMPLES\FLOPPY

Summary

This program is designed to show how to access a physical floppy disk using the Win32 API set.

This program has two major functions.

It can be used to display the geometry of a disk

mfmt -g a:

It can be used to produce a disk image, or to write a disk image to a floppy.

mfmt -c a: bootdisk

Produce a disk image of a:

mfmt -c bootdisk a:

Make a: identical to bootdisk image

This program is very simple. Minimal error checking is done. It is meant to provide an example of how to:

Open a physical disk

Read a disk's geometry

Perform a low level format operation

Read and write physical sectors


  FontView

Font Usage Utility

Location

\MSVCNT\SAMPLES\FONTVIEW

Summary

This is a program 'that illustrates several programming aspects. As a standalone application, it allows developers to experiment with the various parameters to the Win32 CreateFont call, as well as examine the actual fonts and their metrics that are the results of this call.

More Information

This application also illustrates the following programming aspects and capabilities:

CreateFont and other font manipulation usage.

Single source code for Windows 3.x for MS-DOS and Windows NT.

An 'About' box with custom bitmap

Implementing the 'Help' menu to interact with the WinHelp engine

Incorporating a Status Bar in your application

Incorporating a Button Bar in your application


  GDIDemo

GDI Sample Application

Location

\MSVCNT\SAMPLES\GDIDEMO

Summary

The GDIDemo application contains several examples of using GDI calls to generate graphics.


  Generic

Sample Template Windows Program

Location

\MSVCNT\SAMPLES\GENERIC

Summary

This is a sample template that illustrates what could be considered a minimum Windows application.


  GetDev

Get Device Capabilities Demonstration

Location

\MSVCNT\SAMPLES\GETDEV

Summary

The GETDEV sample is a dialog box that displays the result of the GetDeviceCaps() call with all of the possible input parameters. Six of the numeric results (TECHNOLOGY, LINECAPS, POLYGONALCAPS, TEXTCAPS, CLIPCAPS, and RASTERCAPS) are expanded to show the constant string from WINGDI.H.


  GetSys

Get System Information Demonstration

Location

\MSVCNT\SAMPLES\GETSYS

Summary

The GETSYS sample is a dialog box that provides the user with an easy way to see the results of the following API functions:

GetSysColors()

GetSystemDirectory()

GetSystemInfo()

GetSystemMetrics()

GetSystemPaletteEntries()

GetSystemTime()


  GridFont

Unicode Font Selection Demonstration

Location

\MSVCNT\SAMPLES\GRIDFONT

Summary

This application, written in C++, displays a grid containing unicode codepoints. The user is able to select a font, and then see which codepoints are covered by the font.

Notice:

There is a font distributed with Windows NT which covers more than one thousand unicode characters. In order to use this application to its full potential, you will want to install that font using the Control Panel, Fonts item. The font is named L_10646.TTF.


  Hooks

Demonstration of Monitoring System Events

Location

\MSVCNT\SAMPLES\HOOKS

Summary

This sample uses a variety of thread-specific hook procedures to monitor the system for events affecting a thread. It demonstrates how to process events for the following types of hook procedures:

WH_CALLWNDPROC

WH_CBT

WH_DEBUG

WH_GETMESSAGE

WH_KEYBOARD

WH_MOUSE

WH_MSGFILTER

In this sample, the user can install and remove a hook procedure by using the menu. When a hook procedure is installed and an event that is monitored by the procedure occurs, the procedure writes information about the event to the client area of the application's main window.


  Inherit

Redirection of Standard I/O

Location

\MSVCNT\SAMPLES\INHERIT

Summary

The INHERIT sample demonstrates how to redirect standard output and standard error to an anonymous pipe via the SetStdHandle() Win32 API function call. It also demonstrates how to convert the equivalent OS/2 API function calls needed to do this with Win32 API functions.

In the sample, a child process is started whose standard output and standard error handles have been redirected to an anonymous pipe. The parent reads out of this pipe and puts the data to both the console and to a log file specified on the command line.


  Input

Keyboard and Mouse Input Monitoring

Location

\MSVCNT\SAMPLES\INPUT

Summary

This program illustrates the usage of the mouse and keyboard messages. It processes messages generated by mouse and keyboard activity, and displays the values in the client area.


  Locale

International Locale Demonstration

Location

\MSVCNT\SAMPLES\LOCALE

Summary

The LOCALE sample is a simple dialog box that provides an interface between the user and the system via the GetLocaleInfoW() application programming interface (API).


  MaskBlt

GDI Masked Bit Copy Demonstration

Location

\MSVCNT\SAMPLES\MASKBLT

Summary

The MASKBLT sample demonstrates the MaskBlt() Win32 API function. The program presents a dialog box on the top of the window; through this dialog box the user can manipulate the parameters to MaskBlt(). In the main window, the source bitmap is displayed in the center third of the window, the monochrome bitmap mask is displayed in the right third of the window, and the destination bitmap is displayed on the left.

More Information

The destination rectangle may be changed directly in the dialog box, or it may be changed by using the direct manipulation object in the left third of the window. Clicking and dragging the mouse in the upper-left corner moves the rectangle; clicking and dragging the mouse in the lower-right corner sizes the rectangle. The function requires only a starting point (not a rectangle) for the source and mask bitmaps. There is one additional direct manipulation object for the source and one for the mask. These objects may be moved by clicking and dragging with the mouse.

The raster operation for the MaskBlt() call may be changed by altering the values in the right most entry fields. The contents are interpreted to be in hexadecimal. There is a combo box directly beneath these entry fields that lists all of the standard raster operations. If the user selects a standard ROP from this combo box, its contents are copied into the ROP entry.


MDI
  MDI_

Multiple Document Interface Demonstration

Location

\MSVCNT\SAMPLES\MDI_

Summary

The MDI_ sample demonstrates multiple document interface (MDI), associating data to each MDI window, and accelerators.


  Memory

Interprocess Memory Sharing

Location

\MSVCNT\SAMPLES\MEMORY

Summary

The MEMORY sample demonstrates the use of the file mapping APIs to create a share memory between processes.

More Information

Server

The "server" sets up the named share memory. A "server" can be created by selecting the Create.Server menu item.This opens up a MDI child and swaps the menu bar to the server menu bar.

  To set up the equivalent of a named share memory:

1.	Select the Server.Create File... menu item.

This brings up the File Type dialog box. The user may create either a memory page file or a physical file by clicking on the Page File or the Map File button respectively to back up the soon-to-be-created named share memory.

If the Map File button is selected, the named shared memory will be backed up by a physical file on the disk. On the other hand, if the Page File button is clicked, the memory will be backed up by the memory page file.

2.	Select the Server.Create File Mapping... menu item.

This brings up the Map Name dialog box. The user then specify a name for the memory map file object which will be created for the file created in Step 1 above.

This name will be used to identify the shared memory by the clients in the other processes.

3.	Select the Server.Map View of File menu item.

This essentially maps the map file object created in Step 2 above into the process's address space.

4.	Select the Server.Access menu item.

This creates a MLE inside the MDI Server child. Whatever written in the MLE is put in the map file object.

Client

The "client" connects to the named share memory created by the server in another process. A "client" can be created by selecting the Create.Client menu item. This opens up a MDI child and swaps the menu bar to the client menu bar.

  To set up the connection to the named share memory:

1.	Select the Client.Open File Mapping... menu item.

This brings up the Map Name dialog box. The user can then enter the name of the map file object which client wanted to connect to.

2.	Select the Client.Map View of File menu item.

This essentially maps the map file object opened in step 1 above into the process's address space.

3.	Select the Client.Access menu item.

This creates a MLE inside the MDI Server child. Whatever got written in the map file object by the server will be shown in this MLE.

The client synchronizes with the server at a regular interval.

4.	Select the Client.Refresh Now menu item refreshes the contents of the map file object immediately.


  Menu

Menu Demonstration

Location

\MSVCNT\SAMPLES\MENU

Summary

The MENU sample demonstrates many kinds of menu items, including check boxes, owner-draw menus, submenus, and pop-up menus.


  MltiThrd

Multiple Thread Example

Location

\MSVCNT\SAMPLES\MLTITHRD

Summary

To illustrate the usage of Multiple Threads, this program allows the user to open up multiple windows that contain a bouncing square. The movement and drawing of the square, is handled by a separate thread per window.


  MultiPad

Multiple Document Interface (MDI) Example

Location

\MSVCNT\SAMPLES\MULTIPAD

Summary

This application illustrates the Multiple Document Interface (MDI) API that is part of Windows. It functions much like the Windows Applet 'NotePad', but rather then a single edit window, it allows the user to open up multiple windows at a time. Through the use of MDI as a common interface, it also allows the user to organize and maintain these windows in a orderly fashion.


  MyPal

Palette Management Example

Location

\MSVCNT\SAMPLES\MYPAL

Summary

The MYPAL application illustrates a simple usage of the Palette Management API of Windows. In the client area of the application, it presents the current color palette provided by the display driver.


    Named Pipes

Named Pipe Client/Server Demonstration

Location

\MSVCNT\SAMPLES\NPCLIENT

\MSVCNT\SAMPLES\NPSERVER

Summary

NPCLIENT and NPSERVER demonstrate the use of named pipes.

The basic design consists of a server application serving multiple client applications. The user can use the client applications as an interface to all of the other client applications via the server. The effect is a simple communication program that can be used over the network between multiple clients.

More Information

The actual implementation works by having the NPSERVER application launch a new thread, which creates and services a new instance of the server side of the named pipe every time a client connects to it. You need only start one instance of the NPSERVER application. It will service up to 100 instances of the NPCLIENT application. (Note that the 100 instance limit is hard coded into the sample. It does not reflect the number of named pipe instances you can create, which is virtually infinite.)

To Use

Start an instance of NPSERVER. A window will appear.

Start an instance of NPCLIENT. Two dialog boxes will appear, one on top of the other. The top level dialog box will prompt you for a share name and a client or user name. If the instance of NPCLIENT is local to (on the same machine as) the NPSERVER instance, enter a '.' for the share name. Otherwise, enter the machine name of the server that the NPSERVER instance was started on, i.e. 'HelloServer'. For the client or user name, enter any name you wish to be identified with. Hit enter or click the OK button.

The upper dialog box will go away, and you'll see the Client dialog box of NPCLIENT. It consists of two edit fields and a 'Send' button. You will be able to read messages from other clients (and yourself) in the larger/upper edit field. (Note, if the message seems garbled, make sure the cursor of the edit field is located in the lower left hand corner of the field.)  The smaller edit field is used to type messages. To send a message: type something in the lower/smaller edit field, and hit enter or click the Send button. The message will appear in the larger edit field of all the clients connected to the NPSERVER instance; prepended by the user name you selected. Note that the user name you selected will be entered into the caption bar of the NPCLIENT instance. This allows you to more easily keep track of multiple instances of NPCLIENT on the same machine.

At the same time the top level dialog box was dismissed from the NPCLIENT instance, the NPSERVER window was updated with the picture of a red spool of thread accompanied by the user name you selected. This red spool indicates an active client thread connected to NPSERVER. The spool may be connected to other spools with a thin blue line (similar to the way the File Manager connects files or directories). Any time a client disconnects from NPSERVER; the spool representing it will be grayed out.

Design

Basically, the NPSERVER application launches multiple instances of a server thread. When the application is started, the first thread is created. It creates an instance of the server side of the named pipe, and waits for a client to connect. Once a client connects, another thread is started and it too blocks waiting for a client. Meanwhile, the first thread updates a global array of client information with this specific client's information. The thread then enters a loop reading from this client. Any time this specific client sends a message, this server thread will call a function (TellAll) which will write the message to all the clients that have been listed in the global array.

On the client side, NPCLIENT tries to connect to the named pipe with a CreateFile call. Once it has connected, it creates a thread which loops and reads any message from the server side. Once a message is read, it is printed in the larger edit field. Any time the user hits the Send button, the main thread grabs any text in the lower edit field, and writes it to the server.

The steps between NPSERVER and an instance of NPCLIENT looks like this:

NPSERVER	NPCLIENT
CreateNamedPipe()
ConnectPipe() // Blocks
	CreateFile()  //Connects to pipe.
	spawn separate thread to read pipe
return from block
updates array of clients
spawn another server thread
Loop
ReadFile() // Blocks on overlap
	WriteFile() // User hits Send.
return from block
WriteFile() // Broadcast to clients
End loop // When client breaks pipe.
	ReadPipe Thread:
	Loop
	ReadFile()
	block till server broadcasts
	return from block.
	put string in edit field.
	End loop // when server breaks.
The overlapped structure should be used anytime a pipe is expected to block for any length of time on a read or write. This allows the thread to return immediately from a read or write to service any other part of your application. The overlapped structure should also be used on a named pipe anytime you expect to do simultaneous reads and writes. A minor disadvantage of having to use the overlapped structure is that you must update the file pointer in the buffer (or in a file) manually. This is done by manually modifying the offset field of the overlapped structure after each read. The offset is obtained from the GetOverlappedResult call.


  Output

Simple GDI Graphics Demonstration

Location

\MSVCNT\SAMPLES\OUTPUT

Summary

The OUTPUT example application illustrates several GDI function calls including  TextOut, DrawText, Rectangle, Ellipse, Pie, and Arc.


  OwnCombo

Owner-Draw Combo Box Demonstration

Location

\MSVCNT\SAMPLES\OWNCOMBO

Summary

The OWNCOMBO example application illustrates the use of functions and messages for combo boxes and owner draw. The user interface of this example application is fairly self-explanatory except, perhaps, for the text combo box dialog. This readme provides an explanation of this portion of the application's user interface, to help you better interpret the source code.

The text combo box dialog buttons send various messages to the combo box  and the edit control. These buttons allow the user to vary the data sent with each message.

More Information

The following actions are performed by the buttons:

Unsl All

This button unselects any selection in the combo box.

Sel No

This button takes an integer value from the edit control and attempts to select an entry in the combo box given this index value.

Sel Txt

This button takes a text string from the edit control and attempts to select the item with the given text prefix.

Find Txt

This button searches for the text given in the edit control and returns the item number where it was found in the combo box.

Cb Dir

This appends a directory listing of the current directory into the combo box.

Clr It

This clears all the items in the combo box.

Add It

This takes the string given in the edit control and adds it to the combo box

Del It

This deletes the currently selected item from the combo box.

Cpy It

This copies the currently selected item in the combo box to the edit control

Combo Notifications Check Box

When this box is checked, a message box will appear showing what notification codes the combo box is returning to the application in response to the messages sent by the buttons.


  Paths

GDI Paths API Demonstration

Location

\MSVCNT\SAMPLES\PATHS

Summary

The PATHS sample demonstrates the use of paths for drawing, filling, and clipping. The program draws six different figures in the window and labels each one. Each figure is based on the same path re-created six times. The six figures are the result of calling the following Windows functions (with the poly fill mode in parentheses):

StrokePath()

FillPath()

StrokeAndFill()(Winding)

StrokeAndFill()(Alternate)

SelectClipPath()(Winding)

SelectClipPath()(Alternate)


  Platform

Windows Platform Detection Demonstration

Location

\MSVCNT\SAMPLES\PLATFORM

Summary

All Win32 applications need to use GetVersion() to determine whether they're on the Win32s or Win32 platform. GetVersion() sets the high bit of the high word if the application is running on Win32s.

Win16 applications can determine whether there are running on Win32/NT or Win16/MS-DOS by examining the flags return by GetWinFlags(); a unique manifest constant is returned if the application is running in the Windows on Windows (WOW) layer.


  PlgBlt

GDI PlgBlt API Demonstration

Location

\MSVCNT\SAMPLES\PLGBLT

Summary

Win32 offers an API function that will copy a bit image onto an arbitrary parallelogram. Now, for the first time, application programs can trivially rotate or shear bitmaps. The PLGBLT sample is an easy to use demonstration of how this API function may be used.

More Information

The program presents a dialog box on top of the window that displays the input parameters to the PlgBlt function. By choosing the "New Src" or "New Mask" button, the user can select a new bitmap for use as the source bitmap or as the monochrome mask bitmap. The client area of the window is divided into three regions. The region on the left contains the result of the PlgBlt operation. The region in the middle provides the source HDC, and the region on the right provides the mask bitmap for the PlgBlt operation.

In each of the three regions, there is a "direct manipulation object." This object may be picked up and moved by clicking the left mouse button in the top-left corner and dragging. The three objects are restricted in their response to user actions to correctly reflect the parameters to the PlgBlt function. The object in the mask region may be moved only. The object in the source region may be moved or sized. The object in the destination region may be moved, sized, sheared, or rotated. Please see the WXFORM sample for more information on how this direct manipulation is accomplished.


  PolyDraw

GDI PolyDraw API Demonstration

Location

\MSVCNT\SAMPLES\POLYDRAW

Summary

The POLYDRAW sample provides an easy-to-use demonstration of how the PolyDraw Win32 API function works. The user can place points in the window with the left mouse button, and move these points by dragging with the same mouse button. The PolyDraw curve is drawn dynamically to follow the position of the new points.

More Information

To use this program, click the left mouse button at miscellaneous places in the client area. A Polyline call shows exactly where the points were put. By default, the type entered into the type array is PT_LINETO. This can be changed to a PT_MOVETO type by holding down the SHIFT key. It can be changed to a PT_BEZIERTO type by holding down the CTRL key. The resulting purple curve shows the results. There will be no curve when the bezier points do not come in groups of 4, 7, ... , (3n+1).


  PortTool

Win32 Porting Tool Source Code

Location

\MSVCNT\SAMPLES\SDKTOOLS\PORTTOOL

Summary

The porting tool is used to help identify the places in the 16-bit source code that might need to change to make it 32-bit Win32-compatible. The tool provides a brief description of the problem and a possible solution.

More Information

The porting tool has two operating modes.  It can be run interactively or in the background.  The background mode inserts comments in the locations where issues are found.

There is a section of PORT.INI (the file that the porting tool uses to help identify potential issues) available for entering programmer-defined strings. This allows the porting tool to be customized.


  Printer

Printing Demonstration

Location

\MSVCNT\SAMPLES\PRINTER

Summary

The PRINTER sample does the following:

Shows how to print on NT, using both the CreateDC() and the PrinterDlg() methods for acquiring a printer HDC. The user is allowed to print different graphical objects, as well as a complete device font set. An "Abort" dialog is also implemented.

Provides complete device capabilities for all printers & the display.

Provides information (levels 1 and 2) returned by a call to EnumPrinters.

Shows how to enumerate fonts for a particular DC.

Illustrates differences between the various mapping modes.

Demonstrates GDI functionality.

More Information

The main application window contains a menu and a toolbar. The various submenus allow for:

Printcalls

CreateDC to get a device context for the selected printer in the toolbar combo box, and then prints the current graphics options to this DC.

PrintDlg

Calls PrintDlg to retrieve a device context for a printer, then prints out current graphics options to this DC.

GetDeviceCaps

Retrieves device capabilities for device currently selected in toolbar combo box, and displays them in a dialog box.

EnumPrinters

Retrieves level 1 & 2 information returned by EnumPrinters and displays this information in a dialog box.

GetPrinterDriver

Returns level 1 & 2 information returned by GetPrinterDriver (for currently selected printer) and displays this information in a dialog box.

EnumPrinterDrivers

Returns level 1 & 2 information returned by EnumPrinterDrivers and displays this information in a dialog box.

Refresh

Refreshes the contents for the toolbar combo box (changes made in Print Manager will be reflected by this).

About

Application information dialog

Mapping Modes

User selects between different mapping modes

Graphics

User selects different primitives to display

Pen

User can configure size, color, and style of drawing pen

Brush

User can configure size, color, and style of drawing brush

Text color

User can configure color used to draw fonts


  Process

Creating and Terminating Processes

Location

\MSVCNT\SAMPLES\PROCESS

Summary

The PROCESS sample application provides a simple interface to the CreateProcess() and TerminateProcess() functions. In order to create a process the user is presented with a common dialog box for selecting a file. In this case, the file must have an extension of .EXE. Processes which are started are presented in a list box. Any of the processes can be selected in the list box and then terminated.

TerminateProcess() is used to cause all of the threads within a process to terminate. While TerminateProcess() will cause all threads within a process to terminate, and will cause an application to exit, it does not notify DLLs that the process is attached to that the process is terminating. TerminateProcess() is used to unconditionally cause a process to exit. It should only be used in extreme circumstances. The state of global data maintained by DLLs may be compromised if TerminateProcess() is used rather than ExitProcess().


  PView

Process Viewer Source Code

Location

\MSVCNT\SAMPLES\SDKTOOLS\PVIEW

Summary

The PVIEW utility shows how to read the various bits of trivia and statistics from the relating to the various threads and process hanging about on your machine. It also allows you to muck about with the priority of the processes.

Additional Information:

Two list boxes present themselves on startup, these being the list of processes, and when a particular process is selected, the other list box will contain the threads that are associated with the selected process. Clicking on the "Memory Details" button will bring up another dialog that contains more detail on how the memory associated with that process is being used.  Another list box allows you to see how the memory usage breaks down at the DLL level.


  ReadWrit

Read/Write Synchronization Demonstration

Location

\MSVCNT\SAMPLES\READWRIT

Summary

This article refers to the file DATABASE.C, a part of the READWRIT sample, which is one variation of the classical synchronization problem, Reader/Writer. The Reader/Writer problem, first stated and solved by Courtois, involves a shared resource--typically a database. The issue is to allow both readers and writers access to the database without corrupting it.

More Information

Multiple readers are allowed to access the database as long as a writer is not accessing it. However, when a writer is accessing the database, no other readers or writers are allowed access. There are several variations of this problem; the simplest favors readers to the exclusion of writers, and visa versa.

The implementation used by the READWRIT sample allows multiple readers in the database at one time until a writer wants entrance. Then, no other reader can enter the database until this writer is finished. All readers currently in the database, however, can finish. Thus, no starvation of either the readers or writers, which is inherent in simpler methods, will happen.

  To run this sample, type the following at the command prompt:

READWRIT

You will see the values the readers put on the screen. These are a running total of the threads that wrote to the database.


  Regions

GDI Regions API Demonstration

Location

\MSVCNT\SAMPLES\REGIONS

Summary

The REGIONS sample demonstrates various region-related API functions, and allows a user to create rectangular, elliptic, and multi-polygon regions. In addition, hit-testing a region and combining regions using the different region-combination modes is demonstrated.

More Information

When the program has started, create a region by choosing one of the items in the Create submenu. At this point, items in the Options submenu will be enabled, and hit-testing, inversion, and other actions can be performed on the region.

When a second region is created, items in the Combine submenu will be enabled. Choosing one of these items causes CombineRgn() to be called with the specified combine mode, and the two regions are merged into one.

It is possible to create up to three regions at a time. Items in the Options submenu always apply to the most recently created (or combined) region. The Erase item deletes all existing regions. Items in the Combine submenu always apply to the two most recently created (or combined) regions.


  Registry

Using API Functions to Access the Registry

Location

\MSVCNT\SAMPLES\REGISTRY

Summary

The MONKEY registry example is a simple utility which demonstrates the Registry API functions needed to access the NT Registry. Monkey can be used to climb up and down the various branches of the Registry tree, displaying the individual key's data values. Monkey can also be used to print specified trees to a file named Registry.txt.

More Information

To use: start an instance of the Monkey. A dialog box will appear with several edit fields, list boxes and buttons. The listbox in the center of the dialog box (labeled CHILD KEYS: at the bottom) will always hold the child keys of the current key. Initially it has four entries, representing the four pre-defined key handles of the Registry: HKEY_LOCAL_MACHINE, HKEY_CURRENT_USER, HKEY_USERS, and HKEY_CLASSES_ROOT. If you double-click any of these entries, or high light it and press the "Next/Down" button; the key that you just selected will appear in the edit field "Key Name", and the children of that selected key will replace the entries in "CHILD KEYS:" list box. I.e. if you select HKEY_LOCAL_MACHINE, that name will be present in "Key Name", and it's children will appear in the list box: HARDWARE, SECURITY, SOFTWARE, and SYSTEM. To proceed deeper into the tree, double-click another child. To back out of the Registry, double-click the ".." at the top of the listbox, or press the "Back/Up" button.

If the current key has values associated with it, the name of the values will be listed in the right hand listbox (labeled "VALUES:"). If it has now values, "VALUES:" will be followed by a "0". Once you come upon a key that does have values associated with it, you can double-click any of the values in this list box. At the bottom of the dialog box are two edit fields: "Value: Data Type", and "Value: Data Entry". By double-clicking a value entry, these edit fields will be filled in the data's type and the data's value. I.e. if you follow the tree down to HKEY_LOCAL_MACHINE\HARDWARE\DESCRIPTION\System; and double-click the entry "1) Identifier", the "Value: Data Type" field will be filled with "REG_SZ: A null-terminated Unicode string"; and the "Value: Data Entry" may be filled in with something such as "AT/AT COMPATIBLE"

If the current key has a Class type associated with it, it will appear in the "Class" edit field. The "ACL" edit field is not implemented with this release of the Registry Monkey.

You can use the Registry Monkey to write any part of the Registry Tree to a file called REGISTRY.TXT. To do this, select either the "Full" or "Trimmed" buttons (this specifies either writing all of the key entries, or only those having Value data associated with them); and press the "Print Branch" button. The Registry Monkey will begin at the current branch, and will proceed recursively down the branches to the end of the tree, writing the information to the file. To write the entire tree, print each of the four pre-defined keys. Note, this can make for a rather large file (700Kb at the time this was written).


  Select

Simple DLL Demonstration

Location

\MSVCNT\SAMPLES\SELECT

Summary

This program is a simple illustration of how to construct a DLL


  SetInfo

File Information Demonstration

Location

\MSVCNT\SAMPLES\SETINFO

Summary

The SETINFO sample shows how to get and set information on file date, time, attributes, and size. SETINFO demonstrates much of the functionality of OS/2's DosQFileInfo() and DosSetFileInfo().

More specifically, the SETINFO sample shows how to set file attributes and how to modify file and date times (and how to do the conversions from file time to DosTime, and so on). To use the sample file, enter a filename in the appropriate edit field and choose the Get Info. button. To set file attributes or file date and time information, modify the values in the edit fields and check buttons, and choose the Set Info. and Set Attr. buttons. To slow down the return code reporting, enter a larger value into the time edit field, and choose the Set Time button.


  Service

Services Demonstration

Location

\MSVCNT\SAMPLES\SERVICE

Summary

The SERVICE sample demonstrates how to create and install a service.

In this particular case, the service merely opens a named pipe of the name \\.\pipe\simple, and waits for traffic. If it receives anything, it surrounds the input with:

Foo! [<input goes here>]

and sends it back down the pipe to the client.

The service can be Started, Stopped, Paused, and Continued.

More Information

To install the service, first compile everything, and then user INSTSRV to install SimpleService as follows:

instsrv SimpleService <location of simple.exe>

Now all you have to do is start it, either using the "net start" method or via the control panel Services applet.

Once the service has been started, you can use the CLIENT program to verify that it really is working, using the syntax:

client \\.\pipe\simple foo

which should return the response:

Foo! [foo]

If, after playing with the sample you wish to remove the service, simple say:

instsrv SimpleService remove

Note that INSTSRV can be a little dangerous -- it'll install and remove any service you tell it to, so be careful.


ShareMem
  ShareMem and OthrProc

Shared Memory Demonstration

Location

\MSVCNT\SAMPLES\SHAREMEM

\MSVCNT\SAMPLES\OTHRPROC

Summary

SHAREMEM and OTHRPROC are two samples that work together to demonstrate sharing named memory between two separate processes. These samples must be run together.

More Information

  To use these samples:

1.	Start an instance of SHAREMEM.

A window will appear, which is divided into an upper and lower section. The upper section has two edit fields: one displaying the mouse pointer's X-coordinates and the other the pointer's Y coordinates, as the mouse moves in the lower section.

2.	Start an instance of OTHRPROC.

3.	Allow OTHRPROC to keep focus, but move the pointer around over SHAREMEM's window.

OTHRPROC has a window configuration similar to SHAREMEM; however, you will notice that the X and Y coordinates of the mouse as it moves over the SHAREMEM window are the values that appear in the edit fields of OTHRPROC. To emphasize this, a cross hair will appear in OTHRPROC's lower section; its movements relative to the mouse position in SHAREMEM's window.

When SHAREMEM is started, it allocates a piece of named shared memory the size of a DWORD (the size needed to hold the mouse cursor's X and Y coordinates) using CreateFileMapping. As the mouse pointer is moved across the window, the WM_MOUSEMOVE messages are trapped, and the coordinates are written to the upper edit fields and to the piece of named shared memory.

When OTHRPROC is started, it gets access to the named shared memory by calling OpenFileMapping and MapViewOfFile. OTHRPROC then uses a thread to pool and read the X and Y coordinates written to the shared memory by SHAREMEM. It captures the coordinates and draws a bit map of a cross hair in the specified location.


  ShowDib

Opening and Displaying Device Independent Bitmaps (DIBs)

Location

\MSVCNT\SAMPLES\SHOWDIB

Summary

This sample application illustrates how to deal with Device Independent Bitmaps (DIBs), and do proper palette management.


  SidCln

Demonstration of the Win32 Security API Functions

Location

\MSVCNT\SAMPLES\SIDCLN

Summary

The SIDCLN sample demonstrates some of the Win32 security API functions, and provides a sample of how a utility could be written that recovers on-disk resources remaining allocated to deleted user accounts.

More Information

The on-disk resources recovered are:

Files that are still owned by accounts that have been deleted are assigned ownership to the account logged on when this sample is run.

ACEs for deleted accounts are edited (deleted) out of the ACLs of files to which the deleted accounts had been granted authorizations (eg., Read access)

It may be that running this sample as a utility has no practical value in many environments, as the number of files belonging to deleted user accounts will often be quite small, and the number of bytes recovered on disk by editing out ACEs for deleted accounts may well not be worth the time it takes to run this sample. The time it takes to run this sample may be quite significant when processing an entire hard disk or partition

To Use

You must log on using an account, such as Administrator, that has the privileges to take file ownership and edit ACLs.

The ACL editing part of this sample can only be exercised for files on a partition that has ACLs NT processes:  NTFS

Typical Test Scenario

Create a user account or two, log on as each of these accounts in turn, while logged on for each account, go to an NTFS partition, create a couple of files so the test accounts each own a few files, use the file manager to edit permissions for those files so that each test user has some authorities (e.g., Read) explicitly granted for those files. Logon as Administrator, authorize each test user to a few Administrator-owned files. Delete the test accounts. Run the sample in the directories where you put the files the test accounts owned or were authorized to


  SimplDLL

Simple DLL Demonstration

Location

\MSVCNT\SAMPLES\SIMPLDLL

Summary

The SIMPLDLL sample provides a generic DLL template. Also included are two small test applications, LINKTEST and LOADTEST, which demonstrate load-time linking (to a DLL import library) and dynamic loading, respectively.

More Information

THE_DLL contains a skeleton DLL (dynamic-linked library) entry point and five exported functions with varying parameter lists. A resource file (containing a dialog box template) is also used. You must build THE_DLL.DLL before building LINKTEST.EXE or LOADTEST.EXE.

LINKTEST is a small application that links with the THE_DLL's import library, and allows the user to make calls into THE_DLL (via menu item selections).

LOADTEST is a small application that loads THE_DLL at run time and calls the GetProcAddress function to retrieve the addresses of THE_DLL's exported functions. Again, the user is allowed to make calls into THE_DLL.


  Simple

Minimum Console Application

Location

\MSVCNT\SAMPLES\SIMPLE

Summary

Simple is a minimum example of a Console application. Essentially 'Hello, World'.


  SortForm

DLL Import and Export Demonstration

Location

\MSVCNT\SAMPLES\SORTFORM

Summary

SORTFORM demonstrates the _declspec( dllimport ) and _declspec( dllexport ) keywords by sorting a list of integers. SORTFORM.EXE calls SORT.DLL, which contains the actual code that sorts the integers.

More Information

The SOFTFORM program lets you choose the sorting algorithm, the arrangement of the integers, the number of elements in the list, and how many sorts should be performed. When you push Sort button, the lists are sorted, and the dialog displays the average number of comparisons and swaps per iteration.

You should build SORT.DLL before building SORTFORM.EXE. These projects should also be built in the same directory.

Note that the sorting code used in this demonstration is not necessarily optimal.


  Spy

Message Viewer Source Code

Location

\MSVCNT\SAMPLES\SDKTOOLS\SPY

Summary

The SPY sample provides a demonstration for monitoring system messages sent to a specified window. SPY records the messages and displays them on the specified device. SPY is also useful in debugging for verifying that the messages you think a window is receiving are being received.

SPY demonstrates the following techniques:

1.	Using a system message hook.

2.	Using the new WM_COPYDATA message to pass data to another application.

3.	Reading and writing the Registry.

4.	Creating a thread.

5.	Creating a DLL for the hook.


  StartP

Process Priority Demonstration

Location

\MSVCNT\SAMPLES\STARTP

Summary

The sample STARTP demonstrates how to start a new process at a given default priority. It is a functional replacement for the "start" command, but with added features.

More Information

STARTP starts a separate window to run a specified program. The following is the command syntax for STARTP.

STARTP [/btitle] [/Dpath] [/h] [/l] [/min] [/max] [/c] [program] [parameters]

Parameters

title

Title to display in window title bar. Put entire parameter in quotation marks to include spaces in the title; for example, startp "/Ttest job".

path

Starting directory.

h

Set default to high priority.

l

Set default to low priority.

min

Start window minimized.

max

Start window maximized.

c

Use current console instead of creating a new console.

program

A program to run as either a GUI application or a console application.

parameters

These are the parameters passed to the program.

Note that the priority parameters may have no effect if the program changes its own priority.


  StreBlt

GDI StretchBlt API Demonstration

Location

\MSVCNT\SAMPLES\STREBLT

Summary

The STREBLT sample is an easy to use demonstration of the StretchBlt() API function. The program presents a dialog box on the top of the window, and through this dialog box the user can manipulate the parameters to StretchBlt(). In the main window, the source bitmap is displayed on the right half of the window, and the destination bitmap is displayed on the left half.

More Information

The source and destination rectangles may be changed directly in the dialog, or they may be changed by using the direct manipulation objects in the two halves of the window. Clicking and dragging the mouse in the upper-left corner moves the rectangles; clicking and dragging the mouse in the lower-right corner sizes the rectangles. The source direct manipulation object is temporarily erased before calling StretchBlt() so that the top and left edges do not show in the destination image.

The raster operation for the StretchBlt() call may be changed by altering the values in the right-most entry fields. The contents are interpreted to be in hexadecimal. There is a combo box directly beneath these entry fields that lists all of the standard raster operations. If the user selects a standard ROP from this combo box, its contents are copied into the ROP entry fields and are then used in the StretchBlt() call.

Several of the raster operations make use of a pattern in the destination HDC. For this reason, the program also allows the user to select one of the standard pattern brushes from a second combo box. This brush is selected into the destination HDC just prior to making the StretchBlt() call.

The effect of the StretchBlt() call is also affected by the "StretchBlt mode" that has been set for the destination HDC. A third combo box allows the user to select from any of the standard modes. The difference is most easily observed when stretching from a large source rectangle to a small destination rectangle.

The "Draw" button may be chosen at any time to cause the StretchBlt() call to be made. This does not erase the background, so that the effect of multiple ROPs on the HDC can be observed. Manipulating the source rectangle also causes a StretchBlt() to occur without erasing the window. However, manipulating the destination rectangle erases the destination half of the window before the next StretchBlt() is called.


  Subclass

Control Subclassing Demonstration

Location

\MSVCNT\SAMPLES\SUBCLASS

Summary

The SUBCLASS sample demonstrates how a program can subclass standard controls in order to extend their normal functionality. This sample replaces the window procedure for buttons, edit fields, and list boxes.

More Information

The standard subclassing technique is to replace the window procedure in the window structure by using:

SetWindowLong (hwnd, GWL_WNDPROC, (LONG) SubclassWndProc);

In the SUBCLASS sample, the old window procedure is also saved in a structure pointed at by the user data. Thus, any functionality can be added to various classes of windows without having to know what the class originally was.

In this sample, the subclass procedure adds the ability to move and size the control windows when the application is not in "test mode." When the application is in test mode, the subclass procedure calls the original window procedure and the controls behave as normal. Thus, this sample provides the bare bones for a "dialog editor" type of program.


  TakeOwn

Administrator Security Demonstration

Location

\MSVCNT\SAMPLES\TAKEOWN

Summary

Implements a recovery scheme to give an Administrator access to a file that has been denied to all.

More Information

Must be run from an Administrator account in order to perform reliably.


Threads
  TermProc

Process Termination Demonstration

Location

\MSVCNT\SAMPLES\TERMPROC

Summary

TERMPROC demonstrates how to open and terminate a process, for situations where it is impossible to do so otherwise. You can use PVIEW to get the Process ID (PID) of the process to be terminated.

More Information

TERMPROC accepts either hexadecimal or decimal process IDs.


TermProc
  Threads

Thread Demonstration

Location

\MSVCNT\SAMPLES\THREADS

Summary

THREADS demonstrates how to suspend and resume threads and how to set thread priorities.

More Information

To use THREADS, start the application. Two threads are created: one will draw a red rectangle and the other a green rectangle. Both of these rectangles move about the window; their speeds and behaviors are based on the thread's priority and its resumed/suspended status. The priority and status are set through menu selections.

Of special interest is the suspension count. The system keeps track of the number of times a thread has been suspended and resumed. Each time the thread is suspended, the count is incremented; each time it is resumed, the count is decremented. The suspension count can either be tracked by applications manually, the same way this sample application does, or the return values from ResumeThread() and SuspendThread() can be used to obtain the previous suspension count before the call was made. Only when the suspension count is zero will the thread run.

A thread has only five priorities that you are allowed to use:

THREAD_PRIORITY_LOWEST

THREAD_PRIORITY_BELOW_NORMAL

THREAD_PRIORITY_NORMAL

THREAD_PRIORITY_ABOVE_NORMAL

THREAD_PRIORITY_HIGHEST

Other priorities are reserved for use by the system  Note that THREAD_PRIORITY_HIGHEST will cause the selected thread to receive all of the process's CPU time, causing all other threads, including the user interface, to freeze. If you select this option, use the Windows NT Task Manager or PVIEW to terminate the program .


  Timers

Demonstration of the Windows Timing API

Location

\MSVCNT\SAMPLES\TIMERS

Summary

The TIMERS sample illustrates the use of the SetTimer() and KillTimer() Win32 API functions. Button controls allow a user to start and stop timers, which determine the frequency of flashing rectangles in the client area.


  TLS

Demonstration of the Windows Timing API

Location

\MSVCNT\SAMPLES\TLS

Summary

The TLS sample demonstrates using thread local storage (TLS) to store thread-specific data in a dynamic-link library (DLL). As each thread attaches, the memory is alloc'd and filled. As each thread detaches, it is retrieved; as the process detaches, the TLS is freed.

This is a very basic sample, and the calls into the DLL that cause TLS to be allocated and filled don't really do anything; however, this should be a good basis on which to build TLS.


  TTFONTS

Font Display Demonstration

Location

\MSVCNT\SAMPLES\TTFONTS

Summary

The TTFONTS sample allows you to explore the font system. There is a toolbar on top of the main frame window with buttons that allow the following actions:

1.	Enumerate all of the fonts installed for the display.

2.	Get TEXTMETRIC & OUTLINETEXTMETRIC information.

3.	Create a font based on an arbitrary LOGFONT structure.

4.	Get "font data" by using the GetFontData() API.

5.	Enumerate all of the fonts available to the default printer.

More Information

The program is designed to provide the user an easy interface to the API calls related to the font system. It will not protect against meaningless values, nor will it hide system oddities. Most of the buttons on the toolbar are self explanatory and represent a single system API. Pressing the EnumFonts button will show all of the face names listed horizontally, and each of the fonts within that face name listed vertically below it. TrueType fonts will be marked with a small colored "TT" bitmap. Fonts that have the DEVICE_FONTTYPE bit on will be marked with a small bitmap image of a printer. When the enumeration windows are showing the user can click the left mouse button to copy the information about a selected font into the LOGFONT and TEXTMETRIC dialogs. The user can dismiss this window without changing the dialog boxes by clicking with the right mouse button or typing any character.

The "Display" window is able to operate in any one of three modes. These are listed in the "Display" menu. The first just writes "Hello" in the middle of the screen, and it grids the background. This is useful when utilizing the lfEscapement and lfOrientation fields of the LOGFONT structure. The second mode writes all of the glyphs between the tmFirstChar and tmLastChar values stored in the TEXTMETRIC structure. The final mode is used only for true type fonts. It calls GetFontData, finds the 'cmap' table, and displays glyphs from the different ranges in this table. Use the horizontal scroll bar in the display window to step through the ranges.


  UniPut

Demonstration of the Windows Timing API

Location

\MSVCNT\SAMPLES\UNIPUT

Summary

The UNIPUT sample provides a primitive, mouse-based input method. It allows the user to grab any character covered by a Unicode font, and to drag the character to a second window. If the user drops the character on the second window, that window is sent a WM_CHAR message with the appropriate key code.

More Information

In the UNIPUT sample, the status bar at the bottom of the window shows three fields of information: the title of the last window to receive a WM_CHAR message is on the left; the type of that window, either Unicode or ANSI, is in the center; a list of the most recently dropped characters, sort of a history buffer, is on the right.

There is an online help file, which is built with UNIPUT that contains further information.


  UThunk

Win32s Universal Thunk Demonstration

Location

\MSVC32S\WIN32S\UT\SAMPLE\DB16

\MSVC32S\WIN32S\UT\SAMPLE\DB32

Summary

The DB16 and DB32 samples demonstrate calling a 16-bit DLL from Win32s by using the universal thunking (UT) layer.

More Information

This sample will not run under Windows NT, since the UT calls are supported only by the Win32s extension.


  VirtMem

Demonstration of the Windows Timing API

Location

\MSVCNT\SAMPLES\VIRTMEM

Summary

VIRTMEM is a sample of the various virtual memory API functions available under Win32.

When you start the application, you are initially given a RESERVED page of virtual memory. You can change the protection and state of the page through menu selections. Check marks will appear in the menu items to indicate the current state and protection on the page. More in-depth information regarding the page can be obtained by selecting the Show Page menu item.

The Lock menu item allows you to lock and unlock the page in memory.

The application also uses structured exception handling and allows you to try and write to the page in its various states and protections. To do this, select the Test menu option.


  Walk

Directory API Demonstration

Location

\MSVCNT\SAMPLES\WALK

Summary

WALK is a demonstration of how to recursively find all subdirectories under the current working directory.

More Information

Starting with the current working directory, a call is made to the Walk() function which will find all subdirectories in the current working directory. When a subdirectory is found, the current working directory is changed to this subdirectory and another, recursive call is made to Walk(), which again will find all subdirectories in this new current working directory. Once all subdirectories for the current working directory have been found, the current working directory is changed up one level (..). When the original current working directory is re- entered, then the recursive process stops.


  WinDiff

Graphical Difference Marker Source Code

Location

\MSVCNT\SAMPLES\SDKTOOLS\WINDIFF

Summary

The WINDIFF utility compares two files or directories. It displays the differences in a scrollable window, lining up the identical parts, and marking with color the parts of files which differ. This application can be useful for doing source level management of code.

WinDiff is multi-threaded. It allows the user to interact with the window while the file comparisons are occurring in the background.


  World

Metafile World Coordinate Transformation Demonstration

Location

\MSVCNT\SAMPLES\WORLD

Summary

The WORLD sample demonstrates how an image can be translated and scaled using SetWorldTransform(). The image is read from the metafile.

After the application is started, choose Open from the Metafile menu to specify which metafile should be used. The image is displayed, and the horizontal and vertical scroll boxes ("thumbs") are set to the middle of the scroll bars. Use the scroll bars to translate the image. To scale the image, select the Scale menu option and choose the desired horizontal and vertical scaling factors from the list boxes.

More Information

SetWorldTransform() takes two parameters: a device context and a structure that defines the transform to be applied. The transform contains six fields, which have the following use in this program:

eM11

Horizontal scaling factor

eM12

Not used

eM21

Not used

eM22

Vertical scaling factor

eDx

Horizontal translation

eDy

Vertical translation

The WM_HSCROLL and WM_VSCROLL cases are handled like they are handled in any of the other samples, except that ScrollWindow() is not used to update the window contents. Instead, the appropriate modification is made to the transform, and InvalidateRect() is called to update the window.

When the OK button is chosen in the Scale Image dialog box, the transform is updated and InvalidRect() is called to update the window.


  WSock

Demonstration of the Windows Sockets API

Location

\MSVCNT\SAMPLES\WSOCK

Summary

This sample demonstrates the basics of sockets programming, specifically for Windows Sockets. It demonstrates how to accept incoming connections (via the Windows Sockets Asynchronous Extension APIs, threads and traditional BSD-style blocking calls) and how to connect to remote hosts. Once connected the user can send a text string to the remote host. WSOCK also allows the user to view information on a user-entered host name.

More Information

For the program to operate correctly, the TCP/IP protocol must be properly installed. Also, if two machines are used over a network, both machines must have a "HOSTS" text file (for Windows NT machines, this file is located in %SYSTEMROOT%\SYSTEM32\DRIVERS\ETC\HOSTS; if TCP/IP is installed onto a Windows for Workgroups machine, the HOSTS file is located in C:/WINDOWS/HOSTS). Within each HOSTS file, both the remote and local addresses of both machines must be listed.

WSOCK can run on a single machine (execute two copies of WSOCK) or over a network with two Win32 machines. The following example explains how two separate machines over a network would test WSOCK:

1.	Machine "Bob" executes a copy of WSOCK.

2.	Machine "Fred" executes a copy of WSOCK.

3.	Machine "Bob" chooses one of the Listen menu options (under WinSock) [Listen (Blocking), Listen With Threads, or Async Listen].

4.	Machine "Fred" selects the Connect menu option (under WinSock).

5.	Machine "Bob" enters "12" as a TCP port number.

6.	Machine "Bob" waits for a connection.

7.	Machine "Fred" enters "Bob" as the host name to connect to.

8.	Machine "Fred" enters "12" as a TCP port number.

Both machines are now connected and can send strings back and forth by using the WinSock Send Message menu option.

If "Bob" exits WSOCK while there is a connection, "Fred" will receive a message box notification.


  WXForm

World Coordinate Transformation Demonstration

Location

\MSVCNT\SAMPLES\WXFORM

Summary

The sample named WXFORM provides a demonstration of the new world-coordinate transformation. This sample displays a rectangle in world coordinates and a matrix containing the transform values. Users can directly manipulate the rectangle and see the effect on the transformation, or they can set the transformation and see the effect on the rectangle.

More Information

The program begins by setting the viewport origin to the center of the client area. It then draws a rectangle in world coordinate space from the point (0, 0) to the point (100, 100). The user can directly manipulate this rectangle by using the left and right mouse buttons. Specific actions are described more fully in the "Direct Manipulation Help" dialog box.

There is a second dialog box titled "World Transform." This shows the values of the eM11, eM12, eM21, eM22, eDx, and eDy fields in the XFORM structure retrieved by calling the GetWorldTransform function. By choosing the buttons on this dialog box, the user can cause a SetWorldTransform to occur in the program.

There are three coordinate systems of interest in this sample. The first one is the world coordinate system. These points are ultimately mapped to the second coordinate system, device coordinates, before being painted in the window. This program must also use a third coordinate system, screen coordinates, for certain interactions with the mouse pointer.

There is a third dialog box titled "Mouse Position" that shows the location of the cursor in all three of these coordinate systems. The device coordinates are relative to the upper-left corner of the client area. They are not relative to the viewport origin.