Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

The Win32 Foundation Classes (WFC) - Version 45

0.00/5 (No votes)
16 May 2000 15  
The Win32 Foundation Classes (WFC) are a library of C++ classes that extend Microsoft Foundation Classes (MFC) beyond mere GUI applications, and provide extensive support for system and NT specific applications

Introduction

Win32 Foundation Classes (WFC) is a library of C++ classes that extend Microsoft Foundation Classes (MFC) to do NT specific things. Microsoft has chosen to focus their efforts on making MFC do pretty GUI things rather that application development things. MFC views the world through GUI colored glasses. There's no real support for doing any sort of interesting application in MFC. Oh sure, there's database support but that is GUI-slanted (assumes the application will present the database in a GUI).

Peaceful Coexistence

My strategy in building applications is to divide the problem into two domains, Engine and Interface. The Engine is what does what the application is supposed to do.

Latest Updates

Warning! The versions of WFC distributed from Sam's homepage are in PAX format for reasons of size. The downloadable versions from CodeProject are in the usual ZIP format.

Samples

What's the best way to learn WFC? An example teaches, not much else does. Checkout the samples page.

Codeing Guidlines

WFC was created with these coding guidelines.

The Win32 Classes

CAccessAllowedEntry Encapsulates the ACCESS_ALLOWED_ACE structure.
CAccessControlEntryHeader Encapsulates the ACE_HEADER structure.
CAccessControlList Encapsulates the ACL structure.
CAccessDeniedEntry Encapsulates the ACCESS_DENIED_ACE structure.
CAccessTimeout Encapsulates the ACCESSTIMEOUT structure.
CAppleTalkProjectionResult excapsulates the RAS_PPP_ATCP_RESULT structure.
CBase64Coding Simple base64 encoder/decoder. This is what MIME uses to send binary data in e-mail.
CBitArray Treats bits like they were just any other array. Patterned after CByteArray except it plays with bits instead of bytes.
CBitmapCoreHeader Encapsulates the BITMAPCOREHEADER structure.
CBitmapFileHeader Encapsulates the BITMAPFILEHEADER structure.
CBitmapInfoHeader Encapsulates the BITMAPINFOHEADER structure.
CCommunicationsConfiguration Encapsulates the COMM_CONFIG data structure.
CCommunicationProperties Encapsulates the COMMPROP data structure.
CCompVars Encapsulates the COMPVARS structure.
CColorAdjustment Encapsulates the COLORADJUSTMENT structure.
CCriticalSectionGuard Locks a CCriticalSection (an MFC class) in the constructor and unlocks it in the destructor.
CCryptographicAlgorithm encapsulates the PROV_ENUMALGS structure.
CCryptographicHash encapsulates the hash portions of the CryptoAPI.
CCryptographicKey encapsulates the key portions of the CryptoAPI.
CCryptographicProvider encapsulates the cryptographic provider portion of the CryptoAPI.
CCryptography This is the base class for all cryptographic classes that provide functionality.
CDataChunk Allows for handling of data chunks. Patterned after RIFF.
CDataFile A derivative of CFile that makes it easy to read/write CDataChunk's.
CDataMemory Handles a collection of RIFF chunks.
CDataParser Generic data parsing class.
CDataSocket A derivative of CDataFile that allows you to transmit CDataChunk's over a CSimpleSocket.
CDesktop Encapsulates the desktop API.
CDeviceControlBlock Encapsulates DCB structure used in serial communications.
CDocInfo Encapsulates the DOCINFO structure.
CDragQuery Encapsulates the HDROP handle and API. Useful when handling the WM_DROPFILES message (or OnDropFiles method in MFC).
CDummyFile A class that traps all calls to CFile that would blow up if you weren't a disk file.
CEventLog The event logger. Makes working with log events easier. Allows you to read event log messages, create custom event logs, clear logs, pretty much anything you would ever want to do with an event log.
CEventLogRecord encapsulates the EVENTLOGRECORD structure.
CExtensibleMarkupLanguageAttribute class that encapulates an XML attribute.
CExtensibleMarkupLanguageDocument class that encapulates an XML document.
CExtensibleMarkupLanguageElement class that encapulates an XML element.
CFileDirectory This class gives you the capability to retrieve the names of files (complete full-path filenames) in a directory. You can fill in a CStringArray with the filenames or execute a callback function. You can process the files in a single directory or recurse through the subdirectories.
CFileTime Encapsulates the FILETIME structure/API.
CFileTransferProtocol Makes it a little easier to play with ftp. It retrieves directory listings or files. Easier to use than the MFC counterparts.
CFilterKeys Encapsulates the FILTERKEYS structure.
CGarbageCollector Makes rolling your own copy-on-write objects easy.
CInternetworkPacketExchangeProjectionResult encapsulates the RAS_PPP_IPXCP_RESULT structure.
CInternetProtocolProjectionResult encapsulates the RAS_PPP_IPCP_RESULT data structure.
CListeningSocket Establishes a socket that people can connect to (i.e., makes a server socket).
CLZFile Handles the LZxxx API (compressed files)
CMemoryFile A simple memory mapped file class. It handles the annoyance of mapping a file on an allocation granularity boundary.
CMemoryStatus Encapsulates the MEMORYSTATUS structure
CMicrosoftTape Child of CTape that knows about the Microsoft Tape Format used by NTBACKUP.EXE This is an unfinished class.
CMixer Mixer API stuff.
CMixerCapabilities Encapsulates the MIXERCAPS structure.
CMixerControl Encapsulates the MIXERCONTROL structure.
CMixerControlDetails Mixer API stuff.
CMixerControlDetailsData Mixer API stuff.
CMixerControlInstance Mixer API stuff.
CMixerDestination Mixer API stuff.
CMixerLine Mixer API stuff.
CMixerSource Mixer API stuff.
CMixerSourceSelector Mixer API stuff.
CMixerSpeakers Mixer API stuff.
CMixerSwitchControl Mixer API stuff.
CMixerVolumeControl Mixer API stuff.
CMixerWaveIn Mixer API stuff.
CModem A class that hangs off of CSerialFile that makes it easy to play with modems
CMouseKeys Encapsulates the MOUSEKEYS structure.
CMTFDataBlockHeader Encapsulates the MTF_DB_HDR structure.
CMTFDateTime Encapsulates the MTF_DATE_TIME structure.
CMTFTape Encapsulates the MTF_TAPE structure.
CMTFTapeAddress Encapsulates the MTF_TAPE_ADDRESS structure.
CNamedPipe Unfinished class. Will be derived from CDummyFile
CNetBEUIFramerProjectionResult encapsulates the RAS_PPP_NBFCP_RESULT structure.
CNetwork Base class for all networking functionality.
CNetworkConnectionInformation Class based on CONNECTION_INFO_1 structure. It allows you to enumerate through the people that are connected to your machine.
CNetworkConnections Class that plays with network connections.
CNetworkFileInformation Class based on FILE_INFO_3 structure.
CNetworkFiles Class that plays with network files.
CNetworkInformation Encapsulates the NETINFOSTRUCT structure.
CNetworkResources Class that plays with network resources.
CNetworkResourceInformation Class based on NETRESOURCE structure.
CNetScheduleJob Let's you schedule jobs. It interfaces with the Scheduler Service.
CNetworkSessions Class that plays with network sessions.
CNetworkSessionInformation Class based on SESSION_INFO_502 structure.
CNetworkShareInformation Class based on SHARE_INFO_2 structure.
CNetworkShares Allows you to query machines about their shares, add new shares, delete existing ones, etc.
CNetWorkstation Gathers information about the workstation.
CNetworkUserInformation Encapsulates and combines the USER_INFO_xxx data structures.
CNetworkUsers Plays with the NetUserxxx API. Makes it easy to enumerate, add and delete users.
COFStruct Encapsulates the OFSTRUCT structure.
COperatingSystemVersionInformation Encapsulates the OSVERSIONINFO structure.
COutlineTextMetric Encapsulates the OUTLINETEXTMETRIC structure.
COverlapped Plays with OVERLAPPED structure.
CParsePoint Class that holds a location in s data stream. Used in parsing data with the CDataParser class.
CPasswordChangeFilter A class that makes it easy to intercept password changes.
CPerfCounterDefinition Encapsulates the PERF_COUNTER_DEFINITION structure.
CPerfInstanceDefinition Encapsulates the PERF_INSTANCE_DEFINITION structure.
CPhysicalDiskFile This class makes it easy to read data from a disk in raw format. In other words, this class reads a disk like it was a file without regard to file system on that disk. Want to read an individual sector on the disk? This is the class for you.
CPing A class that allows you to programmatically ping another machine.
CPingResults Holds the results of the ping call
CPixelFormatDescriptor Encapsulates the PIXELFORMATDESCRIPTOR structure.
CQueue A simple thread-safe high-performance data queue. It is designed so that one thread can add to the queue and another can get from it without the two threads blocking on each other.
CPointToPointProtocolProjectionResult encapsulates the RAS_PPP_PROJECTION_RESULT structure.
CPortInformation Provides the same information as PORT_INFO_2 data structures. Used in enumerating ports on a machine (i.e. CNetwork::EnumeratePorts).
CPasswordChangeFilter A class that makes it easy to intercept password changes.
CRandomNumberGenerator Gives you better random numbers than rand(). It has about 900 million starting points, each starting point is good for 10^30 values before it starts to repeat.
CRandomNumberGenerator2 Gives you better random numbers than rand(). It is good for (2^19937)-1 values before it starts to repeat. It is also faster than the other random number generators in WFC.
CRasterizerStatus Encapsulates the RASTERIZER_STATUS structure.
CReedSolomonErrorCorrectionCode Allows you to put a forward error correction code onto a block of data. This class blocks data into 255 byte chunks. Up to 16 of those bytes can be scrambled and the errors will automatically be fixed.
CRegistry Encapsulates the Registration Database (Registry API).
CRemoteAccessService Remote Access Services. Otherwise known as Dial Up Networking. This class allows you to establish connections, hang up connections,
CRemoteAccessServiceAdministration A work in progress. Handles the administration of RAS.
CRemoteAccessServiceAuthenticationMessageBlock Encapsulates the RASAMB structure.
CRemoteAccessServiceConnectionProjection encapsulates the RAS_PORT_STATISTICS structure.
CRemoteAccessServiceInternetProtocol Encapsulates the RASPPPIP structure.
CRemoteAccessServiceInternetworkPacketExchange Encapsulates the RASPPPIPX structure.
CRemoteAccessServiceNetBEUIFramer Encapsulates the RASPPPNBF structure.
CRemoteAccessServicePort Encapsulates the RAS_PORT_0 data structure.
CRemoteAccessServicePortStatistics encapsulates the RAS_PORT_STATISTICS structure.
CRemoteAccessServiceUser Encapsulates the RAS_USER_0 data structure.
CSecurityAttributes Encapsulates the SECURITY_ATTRIBUTES structure.
CSecurityQualityOfService Encapsulates the SECURITY_QUALITY_OF_SERVICE structure.
CSerialFile Treats the serial port like it was a CFile. Makes doing RS232 communications easier.
CServer This class allows you to gather information about a server. It can get you information similiar to the Server Control Panel applet. Decrypts data scrambled by NetServerGetInfo().
CService NT Services class. Makes creating services pretty brainless.
CServiceApplication This class encapsulates all of the logic behind installing, removing and running from a command line (to make debugging easier) needed by a service application.
CServiceConfiguration Basically duplicated QUERY_SERVICE_CONFIG structure.
CServiceControlManager Plays with the Service Control Manager. Allows you to start, stop, install and remove services on the local machine or on a server on the net.
CServiceNameAndStatus Encapsulates the ENUM_SERVICE_STATUS structure.
CSessionInformation Session information based on SESSION_INFO_502 structure. Basically, gives you same info as Control Panel->Server->Users->Connected Users
CSharedMemoryObject Let's you create shared memory segments easily.
CSimpleSocket Base class for TCP/IP sockets. Derived from CDummyFile.
CSimpleSocketFile Turns an existing CSimpleSocket into a CFile. Generally, this is called from CListeningSocket::OnNewConnection()
CSoundSentry Encapsulates the SOUNDSENTRY structure.
CStickyKeys Encapsulates the STICKYKEYS structure.
CSystemAuditEntry Encapsulates the SYSTEM_AUDIT_ACE structure.
CSystemTime Encapsulates the SYSTEMTIME structure/API. It also allows you to get and set the computer's clock.
CTalkingSocket A socket you can use to connect to existing sockets (you connect to a server).
CTape Handles the Tape API. It finally works.
CTapeGetDriveParameters Encapsulates the TAPE_GET_DRIVE_PARAMETERS data structure.
CTapeGetMediaParameters Encapsulates the TAPE_GET_MEDIA_PARAMETERS data structure.
CTapeSetDriveParameters Encapsulates the TAPE_SET_DRIVE_PARAMETERS data structure.
CTapeSetMediaParameters Encapsulates the TAPE_SET_MEDIA_PARAMETERS data structure.
CTextMetric Encapsulates the TEXTMETRIC structure.
CToggleKeys Encapsulates the TOGGLEKEYS structure.
CUINT64 Encapsulates the UINT64 structure.
CUniformResourceLocator Plays with URL's Example: http://www.microsoft.com/hello.html
CUniversalNamingConvention Plays with UNC's Example: \\buckaroo\public\neato\readme.txt
CVolume This class let's you eject removable media (CD-ROM's JAZ drives, tapes, etc). It also let's you lock drives.
CWindowPlacement Encapsulates the WINDOWPLACEMENT structure.
CWorkstationTransport Patterend after WKSTA_TRANSPORT_INFO_0, gives you smurphy information about you network transports (ever wonder what your MAC address is?).
CWorkstationInformation Patterned after WKSTA_INFO_102, used in CNetWorkstation::Enumerate
CWorkstationUser Patterned after WKSTA_USER_INFO_1, used in CNetWorkstation::Enumerate
CXMLArchive This class is modeled after the CArchive MFC class. It allows you to serialize (or persist) objects to and from XML documents.

Classes That Ain't Exactly Win32:

CBubble Creates a tooltip window where ever and how many ever you want.
CCircle Draws a circle on the screen.
CConstellation This ain't exactly Win32 encapsulation of something useful. It is related to CSquiggle but instead of displaying data as a squiggley line across the screen (like an oscilloscope), it displays lots of little dots. It looks like a constellation of stars.
CConstellationData Data to be displayed by CConstellation.
CDrawingObjectGrid A grid of drawing objects like CCircle, etc.
CEllipse Draws an ellipse on the screen.
CGarbageCollector Implements a garbage collection scheme (modeled after COM) that allows objects to govern their own lifetimes.
CLabeledGrid A subclass of CDrawingObjectGrid that adds text labels to the objects.
CPager A virtual base class to handle pagers.
CQueue Implements a thread-safe generic queue.
CRectangle Draws a rectangle on the screen.
CRoundedRectangle Draw a rectangle with rounded corners.
CSkyWord Makes it easy to send messages to SkyTel alphanumeric pagers.
CSprintSpectrum Makes it easy to send text messages to Sprint Spectrum PCS phones.
CSquare Draws a square on the screen. Admittedly not very exciting and ground breaking but I was learning how to do these types of things and was shocked that MFC couldn't do something this simple.
CSquiggle A type of CRectangle that makes creating oscilloscope type displays real easy.
CSquiggleData Data taken from o-scopes to be given to CSquiggle.
CWaitCursor Ye Olde Wait Cursor class. It turns your cursor into an hour glass in the constructor and returns it to normal in the destructor.
CWeather This class normalizes data associated with weather reports.
CWfcTrace Tracing class. Used for adding automagically indented debug statements.

Miscellaneous Functions:

Convert_NERR_Code_to_String Converts NERR_* error codes to text; the FormatMessage() trick doesn't work on these error codes.
bit_clear Macro to set a bit to zero.
bit_set Macro to set a bit to one.
bit_test Test the value of a bit.
wfc_am_i_administrator C Function that returns TRUE if you have Administrator priveleges.
wfc_append_string_to_CByteArray C Function that appends a string to an array of bytes.
wfc_append_text_to_edit_control C Function that appends text to an edit control.
wfc_close_handle C function that returns TRUE if CloseHandle() returns not FALSE. This helps in debugging when you pass an invalid handle to CloseHandle().
wfc_convert_lpcwstr_to_cstring() This eliminated a lot of code in the networking classes. Microsoft (even in Visual C++ version 4.2) has the networking API header files all screwed up. The string parameters are mis-typed. I used to have a lot of code in the classes to detect and fix this but it was real ugly (and prevented const correctness). Adding this function allowed me to fix Microsoft's mistake in one function.
wfc_create_hard_link C function that creates two directory entries for one file. It implements the upcoming NT 5.0 API named CreateHardLink().
wfc_delete_oldest_file C function that deletes the oldest file in a directory. It will return TRUE if a file was deleted or FALSE it a file was not deleted. This is useful in a file cache management system.
wfc_enable_privilege A little routine to enable a specific privilege by name.
wfc_enable_all_privileges A routine I wrote because I hate Microsoft's error messages. They are 100% accurate and totally useless. For example, "Access is Denied." which access is denied???? Another brilliant message was "class failed to initialize" It came from a COM application. Wouldn't it be helpful to know which of the four cudzillion COM object on the system failed to load??? Anyway, wfc_enable_all_privileges simply acquires as many privileges as is possible.
wfc_get_directory_usage_percentage C function that returns an integer percentage of the space used on a volume by a directory. This is useful in a file cache management system.
wfc_get_error_string C function that cryptic error codes into something humanly readable.
wfc_get_executable_directory C function that returns the directory name (ending in a slash) that the executable calling this function exists in. This is good for finding configuration files that must exist in the same directory as the executable.
wfc_get_filename_from_handle C function that returns the file name given a file's handle. It uses the partially documented NtQueryInformationFile to perform this magic.
wfc_get_operating_system_version_string Fills a CString with a nice OS version string (including service pack level).
wfc_get_web_page() Retrieves a URL and puts the page into a CStringArray. This is great for retrieving data from the web.
wfc_move_file_at_reboot() This function let's you schedule a file to be moved at the next reboot. This is how system DLL's are upgraded.
wfc_parse_iso_8601_string This function parses ISO8601 dates into a CTime or COleDateTime object.
wfc_start_screen_saver C function that activates the screen saver.
wfc_undocumented_get_system_process_list Uses an undocumented function to get a list of all processes running in an NT system.

Technical Notes


Frequently Asked Questions

This frequently asked questions (FAQ) document is meant answer the most commonly asked questions about WFC.

1. WFC FAQ Information and Credits

1.1 What is WFC?

WFC started out as a simple little class library that attempts to represent the Win32 API as a set of C++ classes. Over time, more non-Win32 related classes have crept in as I have encountered problems that needed solving. Also, things that have interested me, (like forward error correction) wind up being encapsulated in a generic class and included.

1.2 Who Wrote WFC?

I (Sam Blackburn) did mostly. I have had many people submit bug reports and improvement suggestions. I have incorporated most of those submissions. I can't take credit for other people's work so where ever a bug has been reported and fixed, I include a comment in the code giving thanks to the programmer that found it. I will also surf Internet looking for good freeware code that I can roll into the library. When I do, I try to keep the original author's name in there. I usually wind up rewriting the code to make it more readable (i.e. so I can understand it).

1.3 Did Microsoft Steal Your Name?

Not really. They have a Java product called Windows Foundations Classes (WFC).

2. A Brief History of WFC

2.1 When was WFC Written?

3. Philosophical Questions

3.1 Why is the Source Code so Wordy?

I tend to think of source code as a medium by which humans communicate ideas from one to another. There are a lot of programmers out there that think source code is primarily something that a compiler ingests. The opinion of the programmer producing the code directly relates to the maintainability (and reusability) of that code. If a programmer thinks source code is for compiling, their code tends to be be full of abbreviations and short cuts that save a CPU-cycle here and there. This code is very expensive to reuse. Humans naturally want to solve any given problem using the most knowledge they have at that time. What generally happens is advanced programmers use advanced solutions to simple problems whether or not an "advanced technique" is appropriate. The environment I work in has aggressive delivery schedules. If I cannot reuse code from many dissimilar projects, I will not meet my deadlines. This means in order for code to be quickly reused, it must be painfully obvious what that code does (and in the case of debugging, what that code is supposed to do).

3.1 Which is More Important, Reuse or Object Oriented?

Reuse. I have seen many object oriented (OO) pundits think reuse is a by-product of an OO system. It is not. Reuse is easier with OO designs but all to many times the implementations of those designs are so tied to the original application that reuse is impossible. It is very easy for designers to focus on "solving this problem" when they should be focusing on "solving problems like this."

4. Installation Questions

4.1 How do I install WFC?

See Technical note 2. Note that the WFC zips from CodeProject are in ZIP format, and not in PAX.

5. Build Questions

5.1 How do I build WFC?

See Technical note 2. Note that the WFC zips from CodeProject are in ZIP format, and not in PAX.

5.2 Can I use WFC as a static library?

Yes, go into the WFC project to the Project->Settings->General->Microsoft Foundtion Classes: and select Use MFC in a Static Library. Then recompile everything. Don't forget to change this setting in your project also. If you compile WFC for MFC in a static library, but your project uses MFC in a DLL, you will get linker errors for things like new being multiply defined.

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here