MSDN Magazine > Issues and Downloads > 2001 > November >  Autoplay in Windows XP: Automatically Detect an...
From the November 2001 issue of MSDN Magazine.
MSDN Magazine

Autoplay in Windows XP: Automatically Detect and React to New Devices on a System

Stephane St-Michel and Brian Aust
This article assumes you're familiar with C++ and COM
Level of Difficulty     1   2   3 
Download the code for this article: Autoplay.exe (62KB)
SUMMARY The last few years have seen dramatic growth in digital multimedia content and an increasing number of devices generating such content. Accordingly, the Autoplay feature of Microsoft Windows has been enhanced to handle these scenarios. This article presents samples that use the new features and provides advice on how to take advantage of these additions. The topics covered include Autoplay support for audio CDs and for DVD movies, the Autoplay registration process, event handlers, and how your software can cancel Autoplay when you don't want certain files interrupted. The download includes tools for diagnosing problems and to help the reader understand the shell hardware detection service processing of hardware events.
The primary purpose of Autoplay is to provide a software response to hardware actions initiated by the user on the machine. The Autoplay feature remained roughly the same from Windows® 95 though Windows 2000 and Windows Millennium Edition (Me) because up until recently there have been very few new scenarios with regard to user-initiated hardware events that could trigger a useful Autoplay action. But lately, with the spread of digital multimedia content (music, graphics, and video) and of the many devices to generate or consume that content, many new scenarios are begging for Autoplay to grow. Windows XP reflects the rapid growth of consumer multimedia with an expanded Autoplay feature. In addition to refining the existing Autorun.INF mechanism, audio CD Autoplays, and DVD video Autoplay, support has been added to handle digital music (WMA/MP3), graphics, video, CD burning, video cameras, and other hardware devices.
      In this article, the pre-Windows XP Autoplay will be referred to as Autoplay V1. Autoplay V2 refers to the new Autoplay features introduced in Windows XP. In this article we'll cover Autoplay features for both versions.
      The new features will be illustrated through the sample code available for download with this article. Sample 1 demonstrates a typical application registering to handle volume Autoplay events and enumerating the detected files provided through the IDropTarget interface. Sample 2 demonstrates an application that registers to handle video camera arrival events and also shows how to cancel these Autoplay events. The application could easily be modified to handle other non-volume Autoplay events and cancellation. Sample 3 demonstrates how to cancel all possible volume Autoplay events using the two cancellation mechanisms.

Specifying Autorun.INF Behavior

      If you've installed software from a CD, you've used Autorun.INF. A majority of the setup CDs targeted at the Windows platform use it. The typical user scenario is this: a CD is inserted into the CD drive, the setup program runs automatically, and the user simply follows the on-screen instructions generated by the setup software. Without this mechanism, the user needs to find and open the My Computer folder, find the CD drive, double-click the icon, find the right program to run, and launch it. For novice users, all of these steps are far from obvious and can contribute to the perceived complexity of the PC.
      Autoplay functionality relies on the presence of a file named Autorun.INF located in the root of the volume. The file follows the typical format of Windows INI files and must have an [autorun] section. A simple autorun section might look like this:
[autorun]
open=StartCD.exe
icon=StartCD.exe,-1456
This section can contain one or more of the following values: icon, label, open, ShellExecute, and UseAutoPLAY.
      The icon entry value is a text string. It may contain either a path to an icon (.ICO) file or a path to an executable file followed by a comma and the numeric identifier of the icon resource (resource ID) contained in the file (as I've just shown in the code). If the resource ID is positive, it denotes the index of the resource within the file; if negative, it denotes a resource ID number. References using icon index values may be invalidated if icon resources move within the file. Therefore it is recommended that resource IDs be used instead of index values.
      The label value is simply a string. This value is new to Windows 2000 and Windows Me and will have no effect on prior releases. These two values, icon and label, are used to represent the associated drive in the Windows shell.
      The open value is used to specify the command line that will be executed when some media triggers Autoplay. The value should contain a valid path (relative to the root of the media) to an executable file followed by any required arguments.
      The ShellExecute value was introduced in Windows 2000 and Windows Me. It is similar to the open value, but the command line provided is passed to the ShellExecuteEx API instead of the CreateProcess API. Unlike CreateProcess, ShellExecuteEx works with file associations to run the application associated with the specified file. For example, if you specify readme.txt as the command, ShellExecuteEx will likely run Notepad to edit the readme.txt file. If CDs will be used on versions of Windows that do not support the ShellExecute value, the Autorun.INF file should include both the ShellExecute and open commands.
      Finally, the UseAutoPlay value should be set to 1 for media that want to use the new Autoplay V2 features on platforms that support it. This value was introduced in Windows XP and will have no effect on prior versions of Windows. When this value is present, it will take precedence over the open and ShellExecute values. As with the ShellExecute value, this value should be used with care. It is intended primarily for use with multimedia content for which Autoplay support was added to Windows XP. If the media might be used on earlier versions of Windows, the Autorun.INF file should also provide a value for open, since UseAutoPlay has no effect on Windows versions prior to Windows XP.
      To maintain support for existing media using Autoplay V1 features, Autoplay V2 drops back to V1 behavior in some scenarios. If Autoplay V2 finds an Autorun.INF file without a UseAutoPlay=1 entry, or detects an audio CD or a DVD movie, then Autoplay V2 behaves as Autoplay V1 used to behave.
      Since personalization is a key feature of the Windows XP shell, one of the advantages of Autoplay V2 is that the user can associate favorite applications with the various events and actions provided through Autoplay. Furthermore, as the adoption of Windows XP increases over time, the need for media to support the older Autoplay features will diminish.

Autoplay Support for Audio CDs

      All CD media containing audio tracks are considered to be audio CDs by Windows XP, regardless of the presence of data tracks. Applications that want to handle audio CD events register under HKEY_CLASSES_ROOT\AudioCD. This registration works on all versions of Windows that support Autoplay.
      Windows XP introduces a new registration scheme for audio CDs that allows multiple applications to register for specific Autoplay events and actions. CDs containing music content are a good example. Since music is a popular content type, it is common for multiple music-related applications to be installed on a computer at the same time. Prior to Autoplay V2, the installation of a new application would replace the Autoplay registration of the previously installed application such that only the most recently installed application would respond to Autoplay events, even though both applications were installed on the system.
      To remedy this problem, audio CDs can now use the Autoplay V2 registration. This new registration scheme allows for more than one application to be registered for the same content type and provides ways for the user to pick the preferred application and to change it at will. Coexistence of these applications is now possible.
      Information on how to register for Autoplay V2 is presented later in this article. The Autoplay V1 registration mechanism is still supported for backward compatibility. If an application registers for Autoplay using both the V1 and V2 mechanisms, Windows XP will ignore the V1 registration and use only the V2 registration.

Autoplay Support for DVD Movies

      Autoplay support for DVD movies was added to Windows 98. Autoplay handles audio CDs and DVD movies in similar ways. The primary difference in the handling of CDs and DVD movies is the way Autoplay identifies the media type. Autoplay checks for the presence of the video_ts.ifo file inside the video_ts folder located in the media's root folder. On all versions of Windows that support DVD Autoplay, applications can register under the HKEY_CLASSES_ROOT\DVD key in a process similar to audio CD registration. Also, as described earlier for audio CDs, Autoplay V2 introduces a new registration mechanism for DVD movie handlers.

Automatically Opening Folders

      On Windows Me and Windows 2000, Autoplay V1 opens a folder to display the contents of a newly mounted hard disk drive or to display the contents of network drives mapped through the Map Network Drive menu option in Windows. Likewise, if there is an Autorun.INF file on a CD media and the open or ShellExecute command is not specified, Windows will open a folder on the root of the drive. Starting with Windows XP, Autoplay V2 opens a folder following the insertion of media in a CD drive or removable disk drive if it can't find an Autorun.INF file and the Autoplay V2 content sniffing does not find any known content. Content sniffing is new to Autoplay V2 and is explained later in this article. This behavior also applies to removable hard disks, like USB and 1394 hard disks.

Event Categories in Autoplay V2

      Like its predecessor, Autoplay V2 provides a software response to hardware actions initiated by the user on the machine. The primary difference between Autoplay V1 and V2 is the dynamic nature of Autoplay V2. When determining what actions to suggest or perform in response to an event, Autoplay V2 considers the event in conjunction with the various programs registered on the computer. In contrast, Autoplay V1 would always statically run the same application pointed to in the Autorun.INF file, or play an Audio CD or DVD movie using the respective default application. Two categories of events are handled by Autoplay V2: volume-based device events and non-volume-based device events.
      Volume-based device events are events that affect devices that appear as volumes in Windows XP—that is, all disk drives accessible via Windows file system APIs. This includes CD drives, removable disk drives, hard disk drives, removable media readers, and mass storage devices. Basically, if it shows up under My Computer with a drive letter, it's a volume-based device.
      Non-volume-based devices include, well, everything else. Specific examples of these devices include digital video cameras and portable music players that do not expose their content as a file system supported by Windows XP. This does not mean that all video cameras and portable music players are non-volume devices. For example, newer digital cameras and portable music players that use the USB Mass Storage stack are treated as volume devices since they appear to the system as volumes.
      Digital camera devices which are non-volume devices get special treatment from Windows. Even though they are non-volume devices, they are handled by the Windows Image Acquisition (WIA) component for backward compatibility reasons. For more information on WIA, see: Windows Image Acquisition.

Autoplay V2 on Volume-based Devices

      Figure 1 describes the various types of volume devices. The classification is based on the return values from the Win32® API function GetDriveType.
      Volume devices can also be categorized as removable or not (the device itself, not the media). For example, volume Autoplay considers USB and 1394 hard disks for Autoplay, but does not consider nonremovable hard disks. This mostly eliminates internal disks for which Autoplay would not be appropriate.
      Volume Autoplay V2 relies on sniffing the content of volumes as they arrive, whether they're media for removable media drives or removable hard disks. This sniffing consists of scanning the first four levels of folders from the root of the volume and looking for multimedia content types: music, graphics, and video. If an application registers file extensions for files which are graphics, music, or video, then a PerceivedType value should be added under the file extension key and its value should be set to "image", "audio", or "video", respectively. When Autoplay sniffs media for content types, files which have their extension appropriately tagged will be identified as belonging to the proper content type. For some media, more than one of these content types will be found; these will be referred to as mixed content media.
      Since Windows can read the content of volume devices, registration of applications is done on a per-content type basis rather than on a per-device basis. When an event occurs, Windows determines which action to perform based on the intersection of the applications registered on a per-content type basis and the content types found on the volume through sniffing.

Figure 2 Volume Autoplay Event Prompt
Figure 2 Volume Autoplay Event Prompt

      If the user did not yet specify any preferences, Windows prompts the user to choose one of the applications, as illustrated in Figure 2. If the user has previously selected a preferred application for the event, Windows automatically launches the preferred application. Once the user selects a default application, this preference can be changed through the AutoPlay tab in the volume's properties in My Computer (see Figure 3).

Figure 3 Volume Autoplay Property Sheet
Figure 3 Volume Autoplay Property Sheet

      Let's consider an example to clarify this behavior. When the user inserts a compact flash card containing Windows Media Audio (WMA) files (compressed music files), Windows sniffs the media and finds the music content. The first time the user inserts such content in the compact flash reader, Windows prompts the user to choose an appropriate handler from a list of all applications registered for this content type. Out of the box, Windows XP provides three options when prompting the user: Play using Windows Media™ Player, Open folder to view files, and Take no action. Other applications can register to be included in this list; more on this later.
      The prompt also has an "Always do the selected action" checkbox which, when checked, enables the user to set the selection as the default action to perform for the current content type. Once a preference has been established, the original behavior can be restored by checking the "Prompt me each time to choose an action" checkbox in the device's Autoplay properties (see Figure 3).
      When a volume contains mixed content, the prompt does not offer the "Always perform the selected action" option. In this situation, the dialog contains a list of all applications registered for the type of content found. The "Always perform the selected action" option is not always provided because there are numerous combinations of content which will cause the mixed content prompt to appear. If the content combination is different the next time around, rendering any fixed preference would be inappropriate. For example, assume a user inserts mixed content media containing digital images and video. The prompt presented is the mixed content prompt. If the "Always perform the selected action" option was available and the user indicated they always want to use Windows Slide Show as the viewing application for this content type, then later when the user inserts other mixed content media containing digital video and music. The original preference of using Windows Slide Show is most likely inappropriate for digital video and music. Because of this, users are always prompted to choose an application when mixed content media is inserted into the drive.

Autoplay V2 on Non-volume-based Devices

      The non-volume-based events are events generated by all other non-volume devices. Windows cannot read the content of such devices. It is also possible that such a device does not support the concept of content. Because of these factors, registration of apps for non-volume Autoplay devices is done on a per-device basis rather than a content-type basis.
      When one of these devices is connected to the machine, Windows checks to see if an application has been registered for the device. If the user has not yet specified a preference, he is prompted to choose one of the registered Autoplay handlers (see Figure 4). If the user has already picked a preferred application for the event, that application is automatically launched by Windows.

Figure 4 Non-volume Autoplay Event Prompt
Figure 4 Non-volume Autoplay Event Prompt

      Once a default application has been selected, that preference can be changed by clicking a small icon that appears in the taskbar notification area when the device is connected (see Figure 5). This approach is different from the way preferences are changed for volume-based devices. The difference is necessary as many non-volume-based devices do not appear in the My Computer folder. Thus, there is no place to host the Autoplay property page.

Figure 5 Icon
Figure 5 Icon

Autoplay V2 Registration Mechanism

      Both volume and non-volume Autoplay now support a new registration mechanism for applications interested in responding to media Autoplay events. With this new mechanism, multiple applications may be registered concurrently for events related to the same content type. This concurrent registration provides a more event-related experience for the user. Autoplay settings are stored in the registry. All settings are rooted on the following key:
HKEY_LOCAL_MACHINE\
    Software\
        Microsoft\
            Windows\
                CurrentVersion\
                    Explorer\
                         AutoplayHandlers
      Applications register handlers to handle Autoplay events associated with particular media types. Information required of volume and non-volume handlers is described in Figure 6 and Figure 7, respectively. Figure 8 shows how the information is reflected in the user interface.

Figure 8 Handler Values UI
Figure 8 Handler Values UI

      Handlers contain the information necessary to launch the associated application along with information used in representing that handler in the Autoplay user interface. A handler does not necessarily have a one-to-one relationship with an application. In response to an Autoplay event, the handler wraps the application with information specific to the event. For example, assuming that an application registers for both music and video events, it would register two handlers. The first would handle music and its action text would be something like "Play music." The second handler would handle video and its action text would be "Play video."
      When Autoplay launches an app in response to a volume-based event, the InvokeProgID and InvokeVerb values are passed to ShellExecuteEx. If the application registered for IDropTarget (new to Windows XP), then all the files that were sniffed will be passed to the application through the IDataObject interface.
      To extract the names of the files, query the data object for the clipboard format CFSTR_AUTOPLAY_SHELLIDLISTS defined in shlobj.h, or use TEXT("Autoplay Enumerated IDList Array") directly. The buffer returned contains the Item ID lists for all files enumerated in the first four levels of folders on the volume. No files are filtered out. The purpose of the buffer is to avoid a second enumeration by the handler. A handler implementation is responsible for filtering out the files that it cannot handle. Figure 9 shows a code extract from Sample 1 that performs the enumeration of the sniffed files.
      When a non-volume device generates an event for which an Autoplay handler is registered, Autoplay creates an instance of the component registered through the Autoplay handler. If the executable implementing this component is not already running, the COM infrastructure will launch the application. Among the first things that the launched application should do is register its local server factories with COM. Figure 10 shows edited code from the Sample 2 project that demonstrates how this can be done.
      Notice that the REGCLS_MULTIPLEUSE flag is passed to CoRegisterClassObject. This is done so that subsequent Autoplay events will be handled by the already running executable. Although not mandatory, it is recommended in most cases to avoid launching multiple instances of the same application. Once the class factory is registered with COM, the COM infrastructure creates the object instance and returns it to Autoplay. Autoplay first calls the Initialize method of the IHWEventHandler interface, passing in the InitCmdLine value from the registry.
      Next, the HandleEvent method will be called with the PnP Device Interface ID as the first parameter and an Event Type string as the third. The second parameter is presently reserved and will be either NULL or the address of a zero-length string; it should be ignored. The Event Type string will be either "DeviceArrival" or "DeviceRemoval". Future versions of Windows might introduce new Event Type values. Accordingly, IHWEventHandler implementations should handle or ignore other values gracefully.
      Since the non-volume handlers are invoked from the Shell Hardware Detection service, additional COM registration must be performed with regard to security. The component as well as the application to be invoked must each have an AppID value. The AppID value must specify "RunAs" = "Interactive User" so that the component will be created by COM on the current console session. Without these settings the COM component creation will fail since services do not run in an interactive session. The relevant settings shown here are extracted from Sample2.INF:
HKCR\
    CLSID\
        "{EE1F39ED-8202-443a-91A9-DD42E3434EB5}"
            "AppID"="{3308ACA6-E093-4aef-8F81-5AF99D1939D7}"
    •••
    AppID\
        Sample2.exe"
            "AppID"="{3308ACA6-E093-4aef-8F81-5AF99D1939D7}"
        •••
        "{3308ACA6-E093-4aef-8F81-5AF99D1939D7}"
            "RunAs"="Interactive User"

Autoplay V2 EventHandlers

      Autoplay V2 determines which handlers should be invoked in response to an Autoplay event using another entity, the EventHandler. EventHandlers associate events to handlers, hence the name. They provide a level of indirection enabling the reuse of handlers for many events. For a handler to be shown in the Autoplay prompt or to be invoked in response to a specific Autoplay event, it needs to be registered under the proper EventHandler. Volume-based events use predefined EventHandlers (see Figure 11).
      Non-volume-based events use EventHandlers defined by the implementers of the handler. The only EventHandler defined by default on Windows XP is VideoCameraArrival. Microsoft® Movie Maker is preinstalled on Windows XP Personal and Windows XP Professional and registers an EventHandler for VideoCameraArrival. Therefore, the VideoCameraArrival EventHandler is automatically defined on these platforms. Other applications that want to handle these events can register their handlers under this EventHandler. When an application defines an EventHandler, the handler should be given a meaningful name describing the device or device type it applies to as well as the event it is meant to handle.
      For non-volume devices, an additional registration step may be required. Non-volume devices need to associate their EventHandlers with the device and event they want to handle. This is done through a DeviceHandler. Autoplay uses DeviceHandlers to associate a device's events with an EventHandler. For Windows XP, only two event types are supported for non-volume devices: DeviceArrival and DeviceRemoval. To add an EventHandler to a device's DeviceHandler, create a registry key named EventHandlers, then a subkey named either DeviceArrival or DeviceRemoval, according to the event that the EventHandler will respond to. Then, within this new subkey, create a REG_SZ value that represents the EventHandler. Here you can see the resulting structure in the registry:
•••
AutoplayHandlers\
    DeviceHandlers\
        MyDeviceHandler\
            EventHandlers\
                DeviceArrival\
                    MyDeviceArrival (value)
      MyDeviceHandler is the DeviceHandler for the new device, and MyDeviceArrival is the EventHandler that Autoplay will use to find handlers registered to handle the device arrival events. Both of these values are provided either by the device at installation or by an application that wants to handle the events of a particular device or device type.
      Autoplay determines which DeviceHandler matches which device using a new feature of Windows XP that enables the association of miscellaneous properties to a device's PnP ID. This is also the mechanism used by Windows XP to display a custom icon and label for volume devices in the My Computer folder and in other parts of the Windows UI. This topic is outside of the scope of this article, but you can refer to the Platform SDK documentation for more information on how to do this.

Canceling Autoplay

      To provide a better user experience, it may be necessary in some cases to prevent Windows from triggering Autoplay for a particular media type or device. For example, assume a user is listening to music files on his hard disk using some application. He then inserts an audio CD. In such a case, interrupting the music that's currently playing is probably not what the user expects.
      For non-volume devices, let's assume that the user has indicated (through the user interface) that Application A is to handle video camera events. But for some reason the user prefers Application B for video editing. He opens Application B and begins editing some previously acquired video, then decides to add some newly acquired content to the video being edited. He invokes Application B's import function and is prompted to turn on the video camera to acquire the latest video content from the camera. Usually this would trigger the launch of Application A, the user's preferred application for video camera events. Fortunately, Application B has cancelled Autoplay processing of video camera events while the user is editing video content. In this case, the cancellation of Autoplay processing by Application B has created a better user experience.
      The purpose of Autoplay is not to provide a reaction to every single hardware event, but rather to help the user accomplish specific tasks related to hardware events of interest. When the software reaction would be disruptive to the current flow of work, or just plain annoying, Autoplay cancellation can be invoked.
      Volume and non-volume Autoplay are cancelled in different ways. Furthermore, volume events can be cancelled using one of two methods depending on whether the application is in the foreground. Each one of these cases is explained next.

Volume Autoplay Cancellation

      Since its first incarnation, Autoplay always provided a cancellation mechanism. If the application wants to cancel Autoplay only when it's in the foreground, the application can listen to the QueryCancelAutoplay message. To cancel Autoplay, whether or not it's in the foreground, an application must implement the IQueryCancelAutoplay COM interface. The application then registers a component implementing this interface in the Running Object Table (ROT). The component will be called whenever an event generates an Autoplay action. Figure 12 shows how to register a COM component in the ROT. The code that is shown is extracted from Sample 3.
      The QueryCancelAutoplay Windows message has been around since Windows 95. Beginning with Windows XP, the WPARAM and LPARAM carry information about the drive and the content that triggered the Autoplay. The WPARAM contains the zero-based drive index (a: is 0, b: is 1, and so on). The LPARAM contains a bitmask representing the content types found on the media during sniffing. (See Figure 13 for the possible values defined in shobjidl.h.) An application returns a similar bitmask indicating which Autoplay content types are not to be handled in response to this event.
      The values for these flags begin at two for backward compatibility reasons. Prior to Windows XP, applications were required to return one if they wanted to cancel Autoplay. Sample 3 contains code to determine if the application is running on Windows XP or higher. The code is wrapped in the IsWindowsXPOrGreater helper function.
      The IQueryCancelAutoplay interface shown here is also defined in shobjidl.h:
[
    object,
    uuid(DDEFE873-6997-4e68-BE26-39B633ADBE12),
    pointer_default(unique)
]
interface IQueryCancelAutoPlay : IUnknown
{
    HRESULT AllowAutoPlay([in, string]LPCWSTR pszPath, 
                          [in]DWORD dwContentType,
                          [in, string]LPCWSTR pszLabel, 
                          [in] DWORD dwSerialNumber);
};
      Since it's not limited to the WPARAM and LPARAM of a message for cross-process communication, the AllowAutoplay method provides the same information that the Windows message cancel mechanism does, and more. When applicable, the label and serial number of the media is provided to help the application decide if Autoplay should be canceled. An application can then base its decision to cancel Autoplay on the media serial number and/or media label. Obviously, this information is not available for blank CDs.
      Using the IQueryCancelAutoplay interface in this way can be especially useful to cancel Autoplay for the second or subsequent CD of a multiple CD setup program or game. As a side note, the QueryCancelAutoplay message cancellation mechanism can also be used for this purpose, since these applications are most often in the foreground when the user is required to insert the next CD.
      The AllowAutoplay implementation must return S_FALSE to cancel Autoplay and S_OK to allow it to continue. If a failure code is returned, it is ignored and treated as if the application allows Autoplay.
      It is important to note that all applications are granted a three-second window in which to cancel Autoplay. Any cancellation query response received after this three-second period is ignored and Autoplay proceeds. This is necessary because Autoplay loses much of its value when the period between the triggering hardware event and the software response is too long. Usability studies have demonstrated that users often try to launch an application manually when the period between the media insertion and the Autoplay action extends beyond five to seven seconds.
      Unfortunately, the time delay due to hardware is already quite long on fast CD drives. Ironically, the faster the CD drive, the longer it takes to bring it up to its operating speed. This does not leave much time to query the applications for cancellation requests. Therefore, applications should register for cancellation only when appropriate and return promptly from the AllowAutoplay call. For backward compatibility, the Windows message mechanism is always used before the IQueryCancelAutoplay mechanism. Refer to Sample 3 for a typical implementation of this mechanism.

Non-volume Autoplay Cancellation

      Non-volume Autoplay cancellation is similar to the volume Autoplay cancellation mechanism for non-foreground applications. It uses a COM interface which the application implements and then registers with the ROT. The interface, IHWEventHandler, is the same one that applications implement to handle events (see Figure 14). IHWEventHandler interface is defined in shobjidl.h. (Note that the HandleEventWithContent method is not used in Windows XP. Current implementations should return E_NOTIMPL.)
      Since the registered component will be invoked from the Shell Hardware Detection service which runs in a different session, an additional flag must be passed during the registration when compared to the same session registration used by the volume Autoplay cancellation: ROTFLAGS_ALLOWANYCLIENT. For the ROT's Register method call to succeed with this flag, the component being registered must have the correct security settings. See the section Autoplay V2 Registration Mechanism earlier in this article for information on how to register the AppID information for a component.
      In contrast to when the interface is used to handle an event, the Initialize method will not be called before HandleEvent when the interface is used for event cancellation. The implementation of HandleEvent must return S_OK if it wants to handle the event and thus cancel Autoplay. A return value of S_FALSE indicates to Autoplay that the application is not interested in handling the event. As with volume Autoplay cancellation, Windows allows only three seconds for applications to return from the HandleEvent call. A typical implementation of this cancel mechanism is provided in Sample 2.

Autoplay Diagnostic Tools

      Two tools for download have been provided with the samples accompanying this article. The first one, APDiag.exe, provides some insight into the Shell Hardware Detection service processing of hardware events (see Figure 15). The tool performs two tasks. First it sets the following registry value:
HKEY_LOCAL_MACHINE\
    System\
        CurrentControlSet\
            Services\
                ShellHWDetection\
                    LogFile [REG_DWORD] = 1
      Then the APDiag.exe tool listens for updates to the %SystemRoot%\Autoplay.log file and dumps the changes to its edit box. This tool is mostly useful for diagnosing non-volume Autoplay problems, but it can also be used in some cases to trace volume Autoplay operations.

Figure 15 Diagnostic Tool
Figure 15 Diagnostic Tool

      The second tool is APPMDiag.exe (see Figure 16). This tool performs an Autoplay post-mortem diagnosis of the last Autoplay attempt for a specific drive. It is meant to be used for the diagnosis of volume Autoplay events. As its name implies, it should be run after a volume Autoplay scenario has been carried out.

Figure 16 Post-mortem Diagnostic Tool
Figure 16 Post-mortem Diagnostic Tool

      Both tools are provided as is and are unsupported by Microsoft.

Conclusion

      Autoplay provides users and software with rich mechanisms for interacting with hardware events on the computer. When used properly by applications, Autoplay's open registration mechanism can significantly enhance the user experience with the many devices that connect to the modern PC.
For background information see:
Essential COM by Don Box (Addison Wesley)
Inside COM by Dale Rogerson
Advanced Windows by Jeffrey Richter (both Microsoft Press).

Stephane St-Michel is a Microsoft Software Design Engineer working on the Windows Shell. He likes COM and the opening curly bracket on the line following the 'if' statement. He also enjoys non-computer related activities with his wife Martine and daughter Gen.
Brian Aust is a Microsoft Software Design Engineer at working on the Windows Shell. He enjoys writing solid C++ code, playing basketball, watching the Mariners, playing "stick" with Kirby the cat and hanging out with his wife Dee.

Page view tracker