Code Sample Descriptions

<Obsolete>

The page below is taken from my old site, where all the code samples were described on a single page. This new site recognizes that the old design was simply breaking down, and each sample has its own descriptive page now. If you see something below that you like, click on the ZIP file link to go to the new download page. As soon as I get a chance to fully describe each code sample on its respective page, this page will be declared fully obsolete and removed. Until then, here ya go! 


AltTab.zip

How to determine the Windows Alt+Tab order using a GetWindow loop. The CTaskList class is used to obtain an ordered list of all top-level tasks, along with their associated hWnd and hIcon values. Demo uses these to display a dynamic representation of the system's Alt+Tab dialog. My thanks to Jonathan Wood for banging this around with me!

See also AppIcon.zip and TaskList.zip.

Featured in my Ask the VB Pro column, VBPJ, March 2000.    (13K)


AniCtrl.zip 

A class-based replacement for the Animation control that ships with VB4/5. This one offers features not available in the standard control, plus eliminates the need to ship an OCX! Shows how to play AVIs from resource files, overcoming the major limitation of the Microsoft control. Download size due to several customized AVIs included in samples.

Featured in my COMponent Builder column, VBPJ, January 1998.    (155K)


AppIcon.zip 

Changing the icon on your main form isn't enough for Windows to recognize it as the application's new icon. You also need to change the icon for the hidden top-level window VB uses to control everything. This demo shows how to do that.

See also AltTab.zip and TaskList.zip.

Featured in my Ask the VB Pro column, VBPJ, March 2000.    (7K)


Console.zip  Mar 18, 2004

This is probably the single most comprehensive sample you will find on this site. It literally does everything you would ever want to do with console applications developed under VB5 or VB6! Support is offered through a lightweight class that abstracts the console such that it appears to you, the coder, as any other window object might. You can read standard input, write to standard output and standard error; use any foreground and background colors you wish; resize, reposition, hide, retitle the console window, flip between full-screen and windowed operation, and on and on and on. And, perhaps best of all, you can fully test the application within the IDE!

As you are probably aware, Classic VB doesn't offer native support for console application compilation. There are a variety of options available including two that are free. Matt Curland offers an add-in that was originally published with his (invaluable) book, Advanced Visual Basic 6. My personal recommend would be that you also check out vbAdvance, not only for its free console support, but also for the many other neat capabilities Peter Young has built into it! That's the tool I used to develop the four included samples, and has a permanent place on my Classic VB toolbar.

Packaged with vbAdvance.    (74K)


CmdLine.zip  May 5, 2004

Here's one for the FAQ posters. This one provides a drop-in class that uses the API to retrieve and parse the command line. Point them to this, and they still won't know they could press F1 and type in "Command". This little diddy was actually written in response to someone wondering how to retrieve the name of the EXE that loaded a DLL. Works for that, too!

Updated to include not only a callable DLL, but also full VBA compliance, so it may be used within Microsoft Office apps (or anywhere that supports VBA, really). Also handles embedded spaces within paths, and quoted parameters now.

Featured in my Q&A column, VSM, January 2002.    (13K)


ClipEx.zip  Jul 1, 2002

This sample recreates, with Classic VB code, most of the functionality found in VB's Clipboard object. Why do something like that? Because VBA doesn't offer a Clipboard object! If you're coding VBA in Word, PowerPoint, or Excel, and want to place information on the clipboard, or retrieve it into your own objects or variables, you're pretty much out of luck. Not anymore. Just import these modules into your document, presentation, or spreadsheet and you're ready to go. Supports text and bitmaps right now. If there's interest in adding metafile support, let me know.

As a bonus, this download includes an Excel macro that will convert either an entire spreadsheet or just the highlighted range to a very simple HTML table. If you're sick and tired of all the formatting baggage Excel normally produces, if you'd prefer exported tables that are ready and able to use your own CSS, you really need to check this one out!

Featured in my Ask the VB Pro column, VBPJ, June 2001.    (152K)


ClipFileCopy.zip

A simple little demo of how to "copy" files onto the clipboard, as well as how to read the list of files copied to the clipboard by Explorer or other apps. Includes a reusable module that offers clipCopyFiles and clipPasteFiles functions. Copying files involves building a DROPFILES structure and placing it on the clipboard as CF_HDROP format. Pasting files is much simpler, just querying for CF_HDROP format and then using normal DragQueryFile calls to retrieve the file names.

Featured in my Ask the VB Pro column, VBPJ, December 1998.    (5K)


ClipView.zip 

A broad-ranging sample that demonstrates how to inject your application into the clipboard viewer chain using either a subclassing control or with native VB5 subclassing. Also demonstrates a variety of ways to interpret the data found on the clipboard, supporting most standard formats. Though just a demo, the design is such that private formats may be easily added in, if the format is known.

Featured in Subclass Your Way Around VB's Limitations, VBPJ, September 1995,
and updated for my Ask the VB Pro column, VBPJ, December 1997.    (36K)


CloneObjs.zip

Shows the time-tested way of cloning objects in VB4/5/6. This method uses Friend Let properties to allow new objects to be built, even though some of their properties are read-only to the exterior world. Unfortunately, this methodology will die with the next release of VB.

Featured in my Ask the VB Pro column, VBPJ, December 2000.    (3K)


CustomBlt.zip

Includes the CustomBlt module that supports two custom BitBlt functions -- TransBlt for transparent BitBlt's, and TileBlt to tile a bitmap across a surface. Also includes CPictureDC class which allows you to obtain an hDC from a VB Picture object, thus allowing you to Blt away with images loaded from resource files or anywhere else. 

See also MemoryDC.zip.

Featured in my Programming Techniques column, VBPJ, January 1997.    (78K)


DrvInfo.zip  Mar 7, 2002

Class-wrapped solution to obtaining all pertinent information about logical drives available to the system your application is running on. Shows how to properly use GetDiskFreeSpaceEx, to obtain free, total, and available space, by testing whether it's exported from kernel32.dll and dropping back down to the non-enhanced version if it isn't. Also provides disk serial number, volume name, compression information, file system, and scads of other information. Drop-in module provided if you're only looking to determine drive free space.

Featured in my Ask the VB Pro column, VBPJ, September 1999.    (15K)


DrvMap.zip

A simple little demonstration of how to convert a drive letter to it's UNC sharename. Demo exercises the included DriveLetterToUNC routine, calling it once for each drive from C: to Z: and reporting the results in two listboxes -- one that shows mapped drives with their associated sharename, and the other showing unmapped drives. See also: UncName.

Featured in my Ask the VB Pro column, VBPJ, March 1999.    (7K)


DualList.zip

A handy little custom control that removes all the grunt work of allowing the user to move items between two listboxes. Offers four buttons nominally designated to Add, Add All, Remove, and Remove All items to/from the contained List2 from/to the contained List1.

Featured in my Ask the VB Pro column, VBPJ, August 2001.    (32K)


EditMenu.zip

Contains a simple routine that adds the methods Microsoft forgot to both ordinary and rich textboxes. Fully support Undo; know when it is and when it's not an option. Also shows one method to quickly insure that your Edit menu is context sensitive -- that is, that you're not offering options that don't make sense.

Featured in my Q&A column, VBPJ, December 1997.    (5K)


EnumMsgs.zip

Demonstrates how utilities like Spy++ determine the name of registered window messages. No documented method exists to do this, but documented APIs can be used to enumerate all such messages, retrieving their name and associated value. An extremely simple class is provided, that fires an event for each detected registered message, useful for filling a listbox or similar needs. The nature of this discovery is such that you'll want to build a lookup table or list, rather than determine the message name on-demand. Registered window messages are typically used to communicate between two or more cooperating applications.

Featured in my Q&A column, VSM, March 2002.    (8K)


EnumRes.zip

Demonstrates how to enumerate the resources embedded in any file, and how to display many of the standard types within your VB program. This project uses EnumResourceTypes to determine what sorts of resources are available, then calls EnumResourceNames on each type. Results are displayed in a treeview, and some types may be extracted and viewed. One interesting aspect of this project is it uses Implements to bring an Enum function back into a class/form where it really belongs, rather than restrict you to performing all processing within a standard BAS module. Also included is a module that retrieves textual API error descriptions (as used in ApiErrMsg).

Featured in my Ask the VB Pro column, VBPJ, May 2000.    (28K)


FileInfo.zip

Contains two classes, CFileInfo and CFileVersionInfo, that provide you with all the information you'll need to make intelligent dialogs for your users, and choices for your logic. Sample app replicates the tabbed NT File Properties dialog for any chosen file.

Some of the APIs used include: FileTimeToLocalFileTime, FileTimeToSystemTime, FindFirstFile, GetCompressedFileSize, GetFileVersionInfo, GetFullPathName, GetShortPathName, SetFileTime, SetFileAttributes, SHGetFileInfo, VerQueryValue, and VerLanguageName.

Custom functions include: DoubleToFileTime, FileTimeToDouble, FormatFileDate$, ProperCasePath$, PointerToString$, and PointerToStringW$.

Featured in my Q&A column, VBPJ, August 1997.    (32K)


FindPart.zip

"How do I find out if a particular program is running when I don't know the entire window caption?" Ever asked that question? Then this demo is for you! Provides a custom FindWindowPartial function that returns the handle of the first window that matches your search criteria. You can search for window captions that start with, or contain, any substring you wish. Perfect for apps that show both their own name and the name of the active document in the titlebar.

Some of the APIs used include EnumWindows, FindWindow, GetWindow, GetWindowText, IsIconic, SetForegroundWindow, ShowWindow and more.

Featured in my Programming Techniques column, VBPJ, September 1995
and Ask the VB Pro column, VBPJ, June 1998.
Provided as VB4-16/32 conditionally-compiled source, and VB5 32-bit.    (7K)


Flood.zip

Do you miss the Paint function Microsoft offered in QuickBasic? Here's the Visual Basic equivalent. This download provides both a standard module and a class module, designed for different use patterns, but ultimately doing the same thing -- floodfilling an area within either a Form or a PictureBox control. The flood is accomplished with ExtFloodFill, and offers all the same capabilities and limitations as that API. Nothing too fancy, but a quick easy way to drop this functionality into any app.

Featured in my Ask the VB Pro column, VBPJ, August 2001.    (14K)


FontPre.zip

Ever wondered what's in all those uninstalled TrueType files? Here's the answer. This sample is a full-blown Font Preview utility. One class, CFontPreview, provides all the digging necessary to tear into a TTF file and pull out the information needed to use a temporarily installed fontfile. Unlike a lot of samples here, this one's relatively light on APIs, but even still over 20,000 instructions are carried out on each preview! If you'd like to see what it takes to spelunk into the strange structures within a TTF, check this one out. (Thanks to Mathias Schiffer, VB MVP, for helping decode the TTF file structure!)

Featured in my Ask the VB Pro column, VBPJ, July 2001.    (32K)


ForceFore.zip

Microsoft changed the rules with Win98 and Windows 2000 ("The OS formerly known as NT5"). The SetForegroundWindow API can no longer be used directly to take focus away from another application. This demo offers my own implementation of ForceForegroundWindow -- a VB function that uses AttachThreadInput together with SetForegroundWindow -- to, well, force the issue. While this is in general never a good idea, there are certainly times when it's called for. Please don't abuse it (as Microsoft's applications developers have done so repeatedly that their systems programmers finally got fed up and brought all this about).

Featured in my Ask the VB Pro column, VBPJ, February 1999.    (6K)


FormBdr.zip

This started out to be an exercise in altering a form's borderstyle -- normally a read-only at runtime (ROR) property. It ended up being an opportunity to make darn near all VB form ROR properties read-write, instead! The CFormBorder class manages most of the relevent style bits for any form, as well as offering support for drag-anywhere (rather than simply with the titlebar) and sysmenu anywhere, both useful for captionless forms.

Formerly read-only properties now made read-write include: ControlBox, MaxButton, MinButton, Moveable, ShowInTaskbar, and WhatsThisButton. New form properties added include: AutoDrag, AutoSysMenu, Sizeable, Titlebar, ToolWindow, and Topmost.

CFormBorder.cls was updated to support both normal and MDI forms, showing how to handle event sinking from multiple source types. Additionally, system menu options are fully sync'd with choices MinButton and MaxButton settings. Useful new functions include EnableMenuItem, RemoveMenuItem, GetMenuItemPosition, GetMenuItemState, and GetMenuItemText.

Download includes three demos. Main demo shows all aspects of using the CFormBorder class. Second demo hijacks the NT4 Services dialog, forcing it to appear in the taskbar so that it doesn't get lost under other windows. Third demo shows how to add a 3D border to a "borderless" form without a titlebar.

Featured in my Ask the VB Pro column, VBPJ, November 2000/January 2001.    (23K)


FormPair.zip

Here's one for anyone who adds toolwindows to an application. This shows how to force your toolwindow form to follow the main form around the screen as the user moves it. Also demo'd is an extremely simple method -- just sending a WM_NCACTIVATE message -- to have the main form appear to maintain focus (using the "active" color in its titlebar) while the toolwindow has the actual focus. This sample includes two flavors, the first uses the MsgHook subclassing control, and the second uses native VB5 subclassing (see HookMe).

Featured in my Ask the VB Pro column, VBPJ, December 1999.    (9K)


Fraction.zip

Provides a class that fully-encapsulates rational number operations. If you work with fractions, you need to check this out! Class allows for simple fraction arithmetic -- addition, subtraction, multiplication, and division. Display is controllable as fraction alone, or reduced using whole number lead. Assignment allowed via Numerator and Denominator, or using a floating-point value with maximum denominator specified.

Featured in my Ask the VB Pro column, VBPJ, November 2000.    (11K)


FtpExists.zip

A simple little demo that exercises a number of wininet functions. This shows how to check if a given file exists on an FTP server, and takes advantage of the CNetUrl class to verify user input. Other useful routines include several for decoding system and wininet error messages.

Featured in my Ask the VB Pro column, VBPJ, April 2000.    (19K)


FullDrop.zip 

This demo shows how to force the dropdown list of a combobox to the full height of all the items in the list. It's quite useful for short lists where you want all items visible, such as a list of all twelve months. Unfortunately, due to the way Windows is designed, obtaining the hWnd for the ComboLBox (the listbox that drops down) is impossible without subclassing the combo. This sample uses native VB5 subclassing (see HookMe), but could easily be converted to any subclassing control.

Featured in my Ask the VB Pro column, VBPJ, September 1999.    (11K)


Grabber.zip 

This sample includes four demos, two variations each on two different methods, showing how to add a size grip (aka "grabber" or "shangle") to any window. The more robust method requires subclassing the form, and some non-trivial tracking of resizing and painting. You must tell Windows when the cursor is over the size grip, so that the proper sizing cursor is displayed and sizing actually occurs if the user attempts it. Of the two subclassing demos, one uses the MsgHook subclassing control for quick and dirty understanding of the issues involved, and the other uses native subclassing (available only in VB5 and higher). The two non-subclassing samples use the Marlett font to draw the size grip, and SendMessage to fake the window into sizing mode. One wraps the "shangle" into a UserControl that's incredibly easy to drop right into any existing VB5/6 project!

All source is provided in VB5 format. Special thanks to Brad Martinez and Phil Weber for collaborating on these examples.

Featured in my Ask the VB Pro column, VBPJ, June 1999.    (20K)


Hello.zip

A complete translation, with a few gratuitous enhancements tossed in of course, of Charles Petzold's classic HELLOWIN demonstration. Provides a complete working skeleton of a Windowed application using nothing but API from Sub Main. Enhancements includes support for startup information (windowstate) and provision for returning an exit code. Also includes a batch file useful for testing the DOS errorlevel emitted by any process. Worth checking out, just to understand what trouble you're avoiding if nothing else.

Featured in my Ask the VB Pro column, VBPJ, March 2001.    (13K)


HexDump.zip

This module provides a little routine that's simply invaluable when it comes to deciphering the contents of some random location in memory. Pass a pointer to HexDump along with the number of bytes of interest, and get back a wonderful little dump like this:

=================================================================================
lpBuffer = &h1AC998   nBytes = 256
001AC998  0000  C8 C9 1A 00 F0 C9 1A 00-02 00 00 00 23 BD CA 99  ............#...
001AC9A8  0010  DC 1D D3 11 BD 80 00 10-4B 7A 56 08 08 CA 1A 00  ........KzV.....
001AC9B8  0020  18 CA 1A 00 7D 01 00 E0-28 CA 1A 00 00 00 00 00  ....}...(.......
001AC9C8  0030  5C 00 5C 00 4E 00 54 00-35 00 30 00 2D 00 53 00  \.\.N.T.5.0.-.S.
001AC9D8  0040  56 00 52 00 2E 00 6C 00-6A 00 2E 00 68 00 6F 00  V.R...l.j...h.o.
001AC9E8  0050  6D 00 65 00 00 00 00 00-5C 00 5C 00 4E 00 54 00  m.e.....\.\.N.T.
001AC9F8  0060  35 00 30 00 2D 00 53 00-56 00 52 00 00 00 44 00  5.0.-.S.V.R...D.
001ACA08  0070  6C 00 6A 00 2E 00 68 00-6F 00 6D 00 65 00 00 00  l.j...h.o.m.e...
001ACA18  0080  6C 00 6A 00 2E 00 68 00-6F 00 6D 00 65 00 00 00  l.j...h.o.m.e...
001ACA28  0090  44 00 65 00 66 00 61 00-75 00 6C 00 74 00 2D 00  D.e.f.a.u.l.t.-.
001ACA38  00A0  46 00 69 00 72 00 73 00-74 00 2D 00 53 00 69 00  F.i.r.s.t.-.S.i.
001ACA48  00B0  74 00 65 00 2D 00 4E 00-61 00 6D 00 65 00 00 00  t.e.-.N.a.m.e...
001ACA58  00C0  4C 4D 45 4D 98 C9 1A 00-00 00 00 00 00 00 00 00  LMEM............
001ACA68  00D0  0C 00 1B 00 00 01 08 00-02 00 00 00 03 00 00 00  ................
001ACA78  00E0  00 00 00 00 00 00 00 00-03 00 00 00 D0 D0 1A 00  ................
001ACA88  00F0  B0 4D 1A 00 D0 35 B3 77-15 7E 00 00 59 1F 1D 27  .M...5.w.~..Y..'
=================================================================================

Also included are three functions used to dereference pointers to unicode or ansi strings and dwords. If you ever find yourself dealing with badly documented wild-haired pointers, you'll want this routine at your disposal!

Featured in my Ask the VB Pro column, VBPJ, February 2001.    (2K)


HookMe.zip

A simple little demo of how to do native subclassing in VB5 (or higher). Includes a drop-in module, MHookMe.bas, that's ideal for inclusion in your Templates folder. Add this module to any project, copy a few lines from it to a form, class, or usercontrol, and you're ready to start reacting directly to window messages.

Important Note: You must edit one line of MHookMe before anything will work. That's the way it is. Please read the comments before e-mailing me, okay? <g>

Presented at VBITS'99, San Francisco.    (15K)


HyperLabel.zip 

A full-blown, VB6-authored, usercontrol that provides hyperlink capabilities to text and images. This usercontrol is windowless (in hosts that support that) and features a transparent background. Maintaining a transparent background and tracking hits on the overlying text proved to be quite a challenge, as this source demonstrates. The hyperlink feature includes a slick way to detect when the mouse leaves your usercontrol extent by taking advantage of old-fashioned drag-and-drop.

Featured in my Ask the VB Pro column, VBPJ, August 1999.    (68K)


HyperJmp.zip

An extremely simply little sample that merely shows how to open any given URL using the ShellExecute API to load the computer's default browser to that location. Also shows how to make an intrinsic Label control look and act like a hyperlink.

FAQ. I also answered this at Ask the VB Pro, but this is a functional example.    (6K)


KPIni.zip

Back by popular demand! Over 8000 CompuServe downloads. This one's the original, folks. The ultimate INI file wrapper module for VB3. Don't be fooled by imitations or misappropriated code. Over 40 functions, many demonstrated with included INI editor, provide the means to do anything doable with or to INIs (including System.Ini). Hasn't been modified in nearly 3 years, but then, neither have Win16 OS's. Readily convertible to Win32, with a few Declare edits (no, don't ask -- I haven't done it) and changes of Integer to Long.

Provided as 16-bit VB3 source.    (12K)


Lasso.zip

Two very simple methods of allowing your users to draw a selection rectangle on a Picture box control. One directly within the host form, and another that uses a class to monitor mouse activity and fire an event when a selection is made.

Featured in my Q&A column, VSM, April 2002.    (30K)


ListSearch.zip

A simple little class that provides "type-o-matic" support for ListBox controls. I used to say this sample could "easily" be reworked to provide similar support for ComboBox controls. Little did I imagine just how many oddball behaviors would need to be overcome. Well, I finally got around to adding a new CComboSearch class that adds this support for ComboBox controls as well.

Featured in my Programming Techniques column, VBPJ, January 1996.         
Featured in my Ask the VB Pro column, VBPJ, May 1999.    (15K)


LongScroll.zip

Have you always cursed VB's limit of Integer values for a scrollbar's Value, Min, Max, and *Change properties? Me too. I wrote a class that mapped Long values into these properties for Visual Basic 4 How-To and have now updated it for use with VB5 (or later). The addition of WithEvents allows this to truly be a drop-in class, with no need for the client to notify it on user-interaction. Definitely one you'll want for your toolbox!

Featured in my Ask the VB Pro column, VBPJ, February 2000.    (12K)


LVStyles.zip

ListViews are controls everyone loves to hate. This demo shows a good number of tricks you can use to make your life with ListViews easier. Sort dates and numbers instead of just text (and at a pace 10-20x faster than the KB method!), reorder the columns, toggle extended styles, use checkboxes on each item, the list goes on. As always with benchmarks, make sure that you time the sorts using an EXE rather than from within the IDE.

Important Note: Sorting a listview using the API (as two of the three methods here demonstrate) breaks the synchronization between the ListView object's ListItems collection and what's being displayed in the listview window. In other words, when you query VB's wrapped collection, the order of items returned will not match what's displayed. The only way to work around this "issue" is to go entirely to the API for all listview operations or live with VB's lame sorting options.

Warning: The fastest sort (the "IListItem Hack") is included for educational purposes only! If you're crazy enough to use that code in your application, you will deserve it when Microsoft breaks you. And don't doubt that they will!

Requires v4.70 or higher of comctl32.dll.    (28K)


MapFile.zip  April 29, 2004

This one is one of those perpetual works-in-progress, I'm afraid. Shows how to map a file into the memory space of your process, thus allowing extremely rapid access to the bytes within through standard CopyMemory calls. At this time, I'm providing a drop-in class you may use for your projects, but I've yet to scrape together a suitably generic demo applet to go with it as this sort of activity is most often highly specific to the file format(s) handled by the app under development. If anyone would care to offer suggestions via my Feedback page, I'd be happy to read and consider them!

Featured in my Ask the VB Pro column, VBPJ, October 1999.    (38K)


MdiBack.zip

Fully functional, drop-in ready, VB6 class that handles all the chores of painting a background on an MDIForm. No message hooking required for this solution! It's far superior to the VB4/VB5 method demonstrated in "Visual Basic 4 How To." This solution works by adding a Picture box to the MDIForm at runtime, bypassing the alignment restrictions normally enforced on such MDI hosted controls.

Featured in my Q&A column, VSM, January 2002.    (164K)


MemoryDC.zip  Jul 1, 2002

A drop-in class, CMemoryDC, that provides a virtual canvas for you to do with as you will. In addition to giving you an area to build pictures in memory before sending them to the screen, it also offers the extremely powerful capability of creating a copy of the hBitmap that's held within a StdPicture object thus allowing you to pass it off to APIs that need to assume ownership of that resource. Additionally, you can request that a StdPicture object be created from your in-memory artwork with the simple query of the class's Picture property. If you work with bitmaps, this is a class you need to have. 

Be sure to read the comments carefully before toggling the CMemoryDC.TerminateKillsBitmap property!

Featured in my Ask the VB Pro column, VBPJ, April 2001.    (27K)


MouseEvent.zip

Wraps the mouse_event API up in a handy drop-in class which offers most common mouse needs as methods, suitable for driving a CBT type app. Here, you will find the ability to click a button by hWnd or screen coordinates, move the mouse to any location on-screen, spin the mousewheel, and more. You control the interval between mouse button down and mouse button up. Packaged with a little demo that shows how to slowly move the cursor, following a geometric path, until reaching a button which is then visibly clicked.

Featured in my Ask the VB Pro column, VBPJ, July 2000.    (13K)


MovedMsg.zip

A drop-in ready module provides two methods to display MsgBox dialogs anywhere on screen. Your may choose to use absolute top/left coordinates or to position the dialog centered exactly over any given window. All positioning automatically accounts for situations where the requested position may be wholly or partially off-screen, and corrects to insure the full dialog is visible. MsgBox's popped using either method may be automatically recalled after a specified time-out period. See also: TimedMsg.

Featured in my Ask the VB Pro column, VBPJ, December 2000.    (10K)


NCMetrics.zip

This sample provides a handy little class that offers all the data returned by SystemParametersInfo when used with SPI_GETNONCLIENTMETRICS. This includes the standard border width for forms, the height or width of horizontal or vertical scrollbars, the height of standard and small captions, and a few other metrics. But, perhaps most interesting of all, it shows how to convert a LOGFONT structure to a StdFont object. You'll be able to immediately assign Message, Caption, or Menu fonts to your controls by just instantiating this class and referencing the appropriate property.

Featured in my Ask the VB Pro column, VBPJ, March 2000.    (8K)


NetConnect.zip

Here's one way you can tell whether your application has access to the internet. As promising as InternetGetConnectedState sounds, it's far from a reliable solution in making this determination. This sample uses InternetOpenUrl instead to actually try retrieving data from the web. Of course, it relies on "reliable" web sites to do this, so judgment is still involved. Also included are a module that deciphers WinInet error codes and a method to differentiate between modem, proxy, or LAN access. (See also the vbInet ActiveX Server for a black-box that includes this class.)

Featured in my Ask the VB Pro column, VBPJ, December 1998.    (17K)


NetDomain.zip

A class module built around the DsGetDcName function, first made available in Windows 2000, providing a wealth of information about the domain you're running on and its controllers. Shows how to dereference a pointer to a structure that's returned from this API, picking out the required strings, longs, and even a GUID.

Featured in my Ask the VB Pro column, VBPJ, January 2001.    (6K)
This functionality is only available under Windows 2000.


NetUrl.zip

Provides a drop-in class that cracks a URL into, or creates a URL from, its constituent parts -- scheme (http, ftp, etc.), hostname, path, username, password, extra data, and port -- taking into consideration which characters may need to be escaped. Extremely useful for parsing user input (see FtpExists for an example). Complete sample included to test the CNetUrl class.

Featured in my Ask the VB Pro column, VBPJ, April 2000.    
Featured again in my Q&A column, VSM, July 2002.   (14K)


NetUser.zip

Demonstrates the hoops you must jump through to get VB to call the NetXXX functions. Includes a CNetUser class that fully exercises NetUserGetInfo, NetUserGetGroups, and NetUserGetLocalGroups, returning the information found in USER_INFO_3 and GROUP_INFO_2. Also shows how to call the Unicode versions of GetUserName and GetComputerName. Custom functions provide Unicode and numeric data found at the end of pointers returned by unfriendly APIs. Thanks to Craig Clearman for working through some of these issues with me!

Featured in my Q&A column, VBPJ Special Enterprise Edition, Fall 1997.
Obviously, this is a Windows NT-only sample.    (6K)


NetWksta.zip

Similar to the above, but exercises the included CNetWksta class. Uses NetWkstaGetInfo and NetWkstaUserGetInfo to interrogate the local box for information contained in WKSTA_INFO_102 and WKSTA_USER_INFO_1 (such as domain name, machine name, user name, and so on). More Unicode hoops for VB to jump through. Thanks to Craig Clearman for working through some of these issues with me!

Featured in my Q&A column, VBPJ Special Enterprise Edition, Fall 1997.
Obviously, this is a Windows NT-only sample.    (4K)


ObjArrays.zip

Frustrated that you can't declare an array of your objects using WithEvents? Here are two designs, that both allow this functionality, if not the specific syntax you're accustomed to. The first design uses a notification interface, to be implemented by your client objects, through which your event-raising objects can notify the clients as needed. The second design uses an intermediate notification object, and totally eliminates all circular reference issues. Both designs allow arrays of objects to sink "events" (notifications) within a single routine in the client. Quite useful in the right circumstances. If you'd like to see a full-blown example of the first design put to the test, you may be interested in the CCRP High Performance Timer Objects, as this is how I designed those.

Featured in my Ask the VB Pro column, VBPJ, August 2000.    
Revisited in my Ask the VB Pro column, VBPJ, May 2001. (48K)


OpSys.zip

Use the COpSysInfo class to retrieve all the information provided by the GetVersionEx and more. Upon instantiation, this class calls GetVersionEx, and exposes all members of the OSVERSIONINFO(EX) structure as read-only properties. In addition, Boolean properties are offered to differentiate which operating system is running (IsWin95, IsWin98, IsWinME, IsWinNT, IsWinXP), and two String properties provide a formatted Windows version for ready display. See the "What Operating System IS This?" Tipsheet for a rundown of what to expect under various conditions.

Featured in my Programming Techniques column, VBPJ, September 1996.    (9K)


PassSniff.zip

Shows how to search the system for all windows, top-level and children, that share any given characteristic - in this case, the ES_PASSWORD style. Uses EnumWindows and EnumChildWindows to scan for all windows hiding passwords behind those pesky asterisks, then passes WM_GETTEXT to retrieve the actual password text. That this task is so simple it ought to teach us all a lesson on security!

Featured in my Ask the VB Pro column, VBPJ, February 2000.    (8K)


PolyBtn.zip   

A simple little demo that shows how to create irregularly shaped UserControls. This generates a MaskPicture at run-time using basic trig functions to calculate the vertices of an n-sided polygon, then draws the polygon in a memory device context and converts that to a standard picture object which can be used as the mask.

Featured in my Ask the VB Pro column, VBPJ, September 1998.    (7K)


PrevInst.zip

Two samples, the first a simple one showing how to use WM_COPYDATA to send the command string received by an application to a previously running instance of that application. This allows MDI-type apps to not open new instances each time a user double-clicks their associated data files. Example uses the MsgHook custom control to simplify the demo. Updated to include VB6-specific classnames.

The second sample is an update to the MDI demo that ships with VB5. This one adds command line processing to open a file, also uses WM_COPYDATA to send command line text to a previous instance, and uses native subclassing to receive the WM_COPYDATA message.

Featured in my Ask the VB Pro column, VBPJ, July 1998.    (45K)


PrnInfo.zip

For years, I've seen newsgroup posts asking how to obtain more information about print queues, spooler status, print job information, and so on. This sample tries to incorporate nearly all of these tasks into a neat little package. You'll have drop-in ready classes that replicate PRINTER_INFO_4 structures, DEVMODE structures, JOB_INFO_2 structures, and a lot more. Want to enumerate print jobs? Adjust a job's position in the queue? Receive notification when a print queue is changed? Pause, resume, or purge a print queue? Get or set the default printer in any operating system? This demo has methods for those, and much, much more! 

Some of the demonstrated APIs include: GetPrinter, SetPrinter, EnumPrinters, EnumJobs, GetJob, SetJob, GetDefaultPrinter, SetDefaultPrinter, PrinterProperties, and many more. See also: Spool.

Featured in my Desktop Developer column, VSM, February 2002.    (143K)


ProgBar.zip

The CProgressBar class can be dropped into any VB4 or VB5 app, and possibly eliminate the need for you to ship comctl32.ocx if you're only using the ProgressBar control. This class fully replicates the common ProgressBar control, utilizing a picture box of your choice to draw upon. (See also: StatProg.zip)

Featured in my Programming Techniques column, VBPJ, March 1996.
"Pure VB," as they say. No 16/32-bit APIs to worry about.    (6K)


RegSettings.zip  

Whether you find it embarrassing or enraging that VB's native registry functions force you to use the VB and VBA Program Settings section, you'll love this class that replaces the native SaveSetting, GetSetting, GetAllSettings, and DeleteSetting functions! Besides allowing you to specify your own company name under which you may store each app's settings, these new functions also allow you to set the default value for your section entries.

Featured in my Ask the VB Pro column, "Getting Started with VB", Spring 1998.    (5K)


ResDemo.zip

An example of some of the interesting things you can do with resource files. This shows how to play WAV files from a memory image loaded from your RES. Also demonstrates tiling a bitmap across the back of your form to give it a textured appearance. That naturally raises issues with regard to controls such as option buttons and checkboxes, and those are handled as well. Finally, an example is given on how one might animate a series of icons similar to what Netscape or Internet Explorer does when they're downloading something. This one's big because it contains both a compiled resource file and the resources that went into it. Still, it's the only sample I'm aware of that shows these features.

Featured in my Programming Techniques column, VBPJ, January 1997.    (488K)


Rgb.zip

A very simple little demo that shows how to break apart RGB colors into their constituent red, green, and blue values. Shows several techniques, including one that returns the results of a GetPixel API call in this already broken down pattern. Sample includes lots of gratuitous graphic content (and even gratuitous sounds!) to please the editors at VBPJ who want to "draw the reader in" rather than provide additional printed code listings. 

Featured in my Q&A column, VSM, September 2001.    (154K)


RMenu.zip

Back in early-1996, I wrote this up as the "proper" way to handle context menus. Yet I still see half-baked, moronic solutions, like calling disabling and re-enabling a textbox on MouseDown (see Q191670). Sheesh! The correct way is to simply respond to WM_CONTEXTMENU messages. Period. Here's how.

This demo was originally written for VB3 and VB4, so it uses MsgHook

Featured in my Programming Techniques column, VBPJ, July 1996.    (5K)


RotFont.zip

This shows how to use CreateFontIndirect to pattern a logical font after any StdFont object but with the addition of rotation to any desired angle. It's all wrapped up in the CLogFont class which offers an hFont property that may be selected into any device context. Just set the Font and Rotation properties, select the hFont into any hDC, and start printing text at any angle. CLogFont is also extremely useful within your owner-drawn controls!

Featured in my Ask the VB Pro column, VBPJ, January 1999.    (4K)


RunOnce.zip

Shows how to make the appropriate registry settings so that your application will be started the next time Windows starts. You can specify whether this should occur only once or at every login, and whether it should apply only to the current user or all users.

Featured in my Ask the VB Pro column, VBPJ, March 1999.    (12K)


Shell32.zip

Three techniques to achieve that ultimate FAQ -- Shell and Wait -- under Win32. GetModuleUsage doesn't cut it anymore. Includes one method to avoid a hanging DOS box so kindly telling you its "Finished." Demonstrates OpenProcess, WaitForSingleObject, GetExitCodeProcess, GetWindowThreadProcessId, and related APIs.

Featured in my Ask the VB Pro column, VBPJ, February 1998.    (5K)


Slurp.zip

Uses the vbInet ActiveX EXE server to slurp a user-supplied list of URLs from the internet to local storage. This is one I wrote for my own use, and is handy to grab all the files linked to from any given web page without going through the motions of clicking on each link, supplying a download location, and generally wasting time. It also serves as a mini-tutorial in one use of vbInet (and is also included in that download).

Unlike most demos on this site, I also employed a tool that I didn't write. Brad Martinez has written an excellent Browse Dialog Server, and made it available via the Common Controls Replacement Project web site. It's not necessary to the operation of this demo, as it's only used to select a destination folder for the slurped files. But it's slick, and I think you'll thank me later for pointing you to it!

Uses features found only in Internet Explorer v4.0 and higher.    (16K)


Splash.zip

Let your About box form serve double-duty as a Splash screen too! This demo shows how to transform your About box into a Splash screen during Sub Main. It just takes a few tricks, such as hiding the OK button and Close menu to make your Splash screens appear much more professional.

Featured in my Ask the VB Pro column, Getting Started with VB, Spring 2000    (26K)


Spool.zip 

Demo includes a utility module that allows submission of print files/data directly to the Windows 95/NT print spooler.   Demonstrates OpenPrinter, StartDocPrinter, StartPagePrinter, WritePrinter, EndPagePrinter, EndDocPrinter, and ClosePrinter. See also: PrnInfo.

Featured in my Ask the VB Pro column, VBPJ, February 1998.    (5K)


StatProg.zip

This sample enhances the CProgressBar class, adding support for it to embed a progress bar within the status panel of a standard StatusBar control. The CProgressBarEx class uses simple VB-based graphics to emulate a progress bar on any PictureBox. It also offers a Host property which accepts a StatusBar to embed the rendered progress bar into. Setting the TextOnly property to True causes the status bar panel to revert to "normal" behavior.

Featured in my Ask the VB Pro column, VBPJ, March 1998.    (12K)


StopWatch.zip

Tired of lame benchmarks? Here's a class module that actually provides you with both meaningful and simple methods to time your code. CStopWatch uses the multimedia timer to provide 1 millisecond resolution in your benchmarks. Check out the tipsheet to see how easy this is to use! 

   (1K)


StrBldr.zip  Apr 23, 2004

A drop-in CStringBuilder class offers an amazing performance boost for repetitive string concatenations. These results are achieved by working within a single oversized memory buffer, rather than repeatedly allocating and deallocating string space. CStringBuilder is modeled after the StringBuilder class in Microsoft's new dotnet platform. If you're building XML or HTML from tables, you owe it to yourself to take a look at this method. The additional bonus being it will prepare your existing Classic VB code base just a little bit more for the move to dotnet, should you be thinking of going there.

This class was updated to add a new Adaptive Resizing technique following a long newsgroup thread on optimizing string building operations. New properties include SizingMethod and SizingPercent, and the adaptive method is now the default whereby each time the buffer size is increased it is adjusted by X% of its current size rather than a fixed number of bytes.

Featured in my Ask the VB Pro column, VBPJ, May 2001.    (20K)


SyncEvts.zip

Examples of three different ways to share events amongst multiple objects. For this demo, timers are shared by multiple instances of an extremely simple clock control. But the event being shared isn't what's important, rather it's the techniques used to share the events (which could be any sort of system callback, or whatever). The methods used include sharing a global form instance with an intrinsic timer control on it, a global class instance that raises events in response to a system clock callback, and a collection-based method that fires secondary interface methods of each member in response to system clock callbacks. By using a secondary interface, different sorts of objects can all receive notifications via a simple loop.

Featured in my Black Belt Programming column, VBPJ, August 1998.    (36K)


SysSnd.zip

A simple little demo that shows how to enumerate the registry to extract all Sounds associated by applications and utilities, including the system sounds. Also, of course, shows how to play them. Functions include playing a WAV file by name and by system alias. Also included are simple routines to start and stop MIDI files.

Featured in my Ask the VB Pro column, VBPJ, August 1998.    (5K)


TaskList.zip    Oct 26, 2001

Shows how to use EnumWindows to iterate through all the top-level windows, filtering to build a Task List replica. Also shows how to get around the lame restrictions on SetForegroundWindow imposed in Win98 and Windows 2000.

Completely rewritten (summer 2000) to recreate the Applications tab of NT's Task Manager. The new and improved CTaskList class now offers both AltTab and TaskMgr modes of window detection, as well as retrieval of window captions and icons. Also shows two ways -- documented automation and undocumented shell32 call -- to invoke the standard system Run dialog.

End Task functionality finally added (summer 2001) to complete the clone of the Applications tab on NT's Task Manager. Works with all varieties of application, including 16-bit WoW tasks running within NTVDMs. Shows how to determine precisely what type of task you're dealing with, and how to enumerate tasks within an NTVDM process. Kills processes gently, by first asking, then insisting, allowing the user the final say-so.

See also AltTab.zip and AppIcon.zip.

Featured in my Ask the VB Pro column, VBPJ, February 1999.
Major updates featured in my Ask the VB Pro column, VBPJ, September 2000.
Featured again in my Desktop Developer column, VSM, September 2001.    (105K)


TextOutline.zip 

This one's really fun! It uses GDI paths to draw the font outlines. All sorts of really wonderful special effects can be created with the CTextOutlineEx class. Properties are offered for FillColor, OutlineColor, and Font, as well as whether the text should be Filled, Outlined, OutlineBehind, and at what Angle. Works with any hDC. You can either use the GDI objects already selected into the hDC, or the class will do that for you. Like I said, really fun!

Featured in my Ask the VB Pro column, VBPJ, July 1999.    (17K)


TimedMsg.zip

Yet another simple little demo that shows how to add a time-out to a standard MsgBox. The only trick to using this is to realize that standard timers are blocked when used within the IDE, but are free to fire in an EXE. A quick call to FindWindow, followed by sending a WM_CLOSE is all it takes. See also: MovedMsg.

Featured in my Ask the VB Pro column, VBPJ, January 1999.    (11K)


TimeZone.zip  May 4, 2004

Shows how to call the GetTimeZoneInformation API, and interpret the returned results. With this code, you can determine the name of the current time zone, whether your app is operating in Daylight or Standard time, what dates these settings are changed, how much the clock is adjusted, and what the offset is from Coordinated Universal Time (UTC).

Featured in my Ask the VB Pro column, VBPJ, April 1999.    (6K)


Translucent.zip

Shows how to create "layered" windows in Windows 2000. This demo provides a drop-in ready class that can be used to either do an Alpha-blend for translucency ranging from totally opaque to completely transparent, or the class can be used to select a single color to be rendered transparent. In either mode, the entire form and all its child controls are affected. Additional demos show how to create an irregularly shaped form using the Color Key approach to layered windows, and how to set the opacity of any window in the system. Now includes updated demos of WinRgn and WndPick, built to show off use of layered windows.

Featured in my Ask the VB Pro column, VBPJ, August 2000.
This functionality is only available under Windows 2000.    (40K)


Tray.zip  Mar 12, 2002

One of the first demos to show how to properly put your 32-bit VB app in the taskbar tray. No hokey mouse messages here. The VB4 demo properly uses a subclassing control to hook the appropriate messages. Also learn how to avoid troubles with popup menus and dialogs. Updated (for latter VSM column) to provide restoration of tray icon after an Explorer crash.

Featured in my Programming Techniques column, VBPJ, November 1996.
Featured again in my Q&A column, VSM, April 2002.    (10K)


TreeRecurse.zip    

Example of how to recursively alter the properties of TreeView Nodes over an entire tree or confined to a single branch and below. This sample expands or collapses all nodes at and below the selected node. This seems an intuitive method for Microsoft to have included with this control, but since they didn't you'll need to use routines such as these.

Featured in my Ask the VB Pro column, "Getting Started with VB", Fall 1998.    (3K)


Twiddle.zip

Just an all-around useful little batch of bit-twiddling routines. Some of these were originally written for Visual Basic 4 How-To and are still as useful as ever. Others evolved out of that work, or just became needed as time went on. All routines are written in "pure VB," with no CopyMemory tricks, to preserve portability to other architectures such as DEC Alpha. This sample shows how to:

  • Set, clear, or check any bit within a Byte, Integer, or Long; 
  • Extract the high and low bytes of an Integer or the high and low words of a Long;
  • Swap the bytes of an Integer or the words of a Long;
  • Rotate and Shift bits within Byte, Integer, and Long variables;
  • Format as, or extract the value from, binary strings;
  • And much more!

The entire package is also bundled up into a class-based hierarchy that's interesting more for the design of it than for any practical use, given the overhead it introduces into calculations you typically need to perform as fast as possible.

Featured in my Ask the VB Pro column, VBPJ, August 2000.    (48K)


UncName.zip

Comprehensive example of how to convert a drive-based filespec to one using Universal Naming Convention (UNC). This is relatively simple if the file resides on a remote network share, but quite complicated if the file is local. Uses WNetGetUniversalName for remote files, and resorts to a best guess after using NetShareEnum for local files. This demo shows the extraordinary lengths one must go to in order to call "the same" function -- NetShareEnum -- on both NT and 9x platforms. See also: DrvMap.

Important notes: Local files present a potential ambiguity, given that a file may exist on several local shares. Another unavoidable problem is that under NT the user must have Administrative privileges for NetShareEnum to return the path of a local share.

Featured in my Ask the VB Pro column, VBPJ, January 2000.    (13K)


WinRgn.zip

Uses CreatePolygonRgn and SetWindowRegion to create an irregularly shaped form. Originally written in VB4/32, but updated with VB5 to add support for dragging the captionless form about the screen. Also demonstrates how to pop the system menu at any arbitrary point. See also: Translucent.

Featured in my Programming Techniques column, VBPJ, April 1996.    (8K)


Wmf2Emf.zip

Perplexed why you can't load a Windows Metafile (WMF) using GetMetaFile or GetEnhMetaFile? Based on an Adobe specification, many applications prepend an additional header to these files that hints at sizing. Here is a module that takes this into consideration, and ultimately converts (in memory) your WMF to the newer Enhanced Metafile (EMF) standard. Using these methods, you should be able to play any metafile onto any device context.

Featured in my Ask the VB Pro column, VBPJ, January 2000.    (38K)


WndPick.zip    Dec 18, 2003

Demonstrates capturing cursor feedback outside your own window. Sample replicates the window picker found in Spy++. A drop target is dragged over the user's choice of windows, and information is returned about the window under the cursor. The last updated added a module that supports outlining any window given just its hWnd. See also: Translucent.

Featured in my Q&A column, VBPJ, September 1997.    (3K)

</Obsolete>