Click here to Skip to main content
Click here to Skip to main content

Trapping windows messages

By , 11 Apr 2003
 

Introduction

To perform some tasks, we still need to trap unmanaged windows messages, even though we are developing managed code. This is a little tutorial that tries to clarify how to trap those messages using the .NET Framework.

The code is written in C#. I believe it will be quite easy for those who are reading this document, and you can use VB.NET™ instead of C#, to port the concepts.

Learn by example

Now, to clarify the concepts lets use something useful. Maybe some of the readers have the need to detect if a CD, or for what matters any removable volume mounted on a device which supports a software ejection method (DVD, Zip, etc…), has been inserted or removed from a device. This can be accomplished by detecting the WM_CHANGEDEVICE message.

Trapping messages in .NET

There are, to my knowledge, two ways of trapping windows messages in the Microsoft .NET Framework.:

The IMessageFilter interface

The most obvious, and I suspect the least useful, is to use the IMessageFilter interface.

The BCL defines an IMessageFilter interface, which describes a single method named PreFilterMessage, which can be used to trap Windows messages. After defining a class which implements the IMessageFilter interface, we just need to tell the Application class, that it should add it to the queue of IMessageFilter interfaces it can handle using the Application.AddMessageFilter method. We can also remove a filter using the Application.RemoveMessageFilter method from the queue. Now, this approach is only useful to trap dispatched messages, it does not handle all messages. This process is out of scope in this document, anyway, as an example example, we would have to use something like:

using System;
using System.Windows.Forms;

public class MyFilter: IMessageFilter
{
    public bool PreFilterMessage(ref Message aMessage)
    {
        if (aMessage.Msg==WM_AMESSAGE)
        {
            //WM_AMESSAGE Dispatched
            //Let’s do something here
            //...
        }
        // This can be either true of false
        // false enables the message to propagate to all other
        // listeners
        return false;
    }
}

At some other point of your code you would have to register an instance of MyFilter, like:

// This will have to have a scope that makes it accessible to both
// AddFilter and RemoveFilter
MyFilter fFilter = new MyFilter();
(…)
Application.AddMessageFilter(fFilter);
(…)
Application.RemoveMessageFilter(fFilter);

Overriding a WndProc method

The solution, in our example, is overriding a WndProc method of a Control or to do the same with an implementation of the NativeWindow class. The first solution is useful if we need to trap messages in a class that inherits the Control class. If we want to build a class that is not dependent on a specific Control, we will have to use the NativeWindow class. This class simply wraps a window handle, and so, it enables us to override the WndProc method which is implemented.

In both cases, we will override the WndProc method like:

protected override void WndProc(ref Message aMessage)
{
    if (aMessage.Msg==WM_AMESSAGE)
    {
        //WM_AMESSAGE Dispatched
        //Let’s do something here
        //...
    }
}

Detecting a volume insertion or removal

Now, let’s look at our example. We already know that we will need to trap the WM_DEVICECHANGED message, and to filter two specific events. We will build the example based on two classes.

The first one, _DeviceVolumeMonitor, will be private to the project, and will only serve to inherit the NativeWindow class, so that our main class won’t expose the public NativeWindow methods. This class will also serve the purpose of encapsulating all API constants and structures that we will need to make things work.

DeviceVolumeMonitor, will be our main class. It implements most of the logic needed to the user. Nevertheless, the main subject of this tutorial is in the other class.

The WM_CHANGEDEVICE message

This message is broadcasted whenever something relevant occurs in a device connected to Microsoft Windows. For this matter, there are two events which we will need to trap, the DBT_DEVICEARRIVAL and the DBT_DEVICEREMOVECOMPLETE.

Both events are handled the same way, the only difference being that DBT_DEVICEARRIVAL detects a volume being inserted, and the DBT_DEVICEREMOVECOMPLETE detects that a volume was removed. Now, we need to look at some of the Win32 API declarations to see how this works.

The WM_CHANGEDEVICE constant definition can be found in WinUser.h, all other information we will need, it can be found in DBT.h header file. Both files are part of the Microsoft Platform SDK.

When a WM_CHANGEDEVICE is broadcasted, the message structure will transport the event value in the WParam, and some additional data in a location pointed by LParam.

As I already described, we are only interested in trapping messages that have a WParam with the DBT_DEVICEARRIVAL or DBT_DEVICEREMOVALCOMPLETE values. The data pointed by LParam will have the same structure in both cases.

Once one of the events is detected, we must cast the pointer stored in LParam, to a _DEV_BROADCAST_HDR structure, and evaluate the dbch_devicetype field. We are only interested in proceeding if the field value is DBT_DEVTYP_VOLUME.

If this is the case, then we will need to cast LParam again, but this time to point at a _DEV_BROADCAST_VOLUME structure. This structure has two fields which we will have to evaluate. The first one is dbcv_flags. This field will tell us the nature of the volume that was mounted (or dismounted). It can be either a media volume like a CD (the flag will have a DBTF_MEDIA flag) or a network share (DBTF_NET). In this case we will only be interested in filtering the DBTF_MEDIA value. The other field is dbcv_unitmask, which is a bit vector that tells us which drive letters were mounted.

At this point, there are two facts which need to be clarified. As stated in the Platform SDK documentation, this message can tell us if more than one volume was mounted and these can be of multiple types. We will have to make an assumption that is whenever the dbcv_flags includes the DBTF_MEDIA value, we will assume that all the drives described by the dbcv_unitmask bit vector are of this type. I don’t think that it is likely that this notification will ever have a dbcv_flags that includes both types. Anyway, this would be solved if we would determine the specific type for all the drives described by dbcv_unitmask. On the other hand, as it was already implied, dbcv_unitmask can describe more than one drive at a time. I guess this is only likely if we have a jukebox device, but anyway this is a problem we will solve in the code.

The _DeviceVolumeMonitor class

This is a helper class which is internal to the project. Now as I told you before, this class is only useful to inherit the NativeWindow class and to encapsulate the API constants and structures we will use. The class constructor takes only a parameter which will be the instance of the main class that owns the _DeviceVolumeMonitor instance.

The API constants and structures were modified to become more readable and useful in the .NET context.

The WndProc is overridden according to the cascading conditions described for the WM_DEVICECHANGE message. If all conditions are fulfilled then the object uses as internal method of the main class to inform it that a valid event has occurred. This method is called TriggerEvents.

The DeviceVolumeMonitor

Our main class, contains some logic, which has no relation to windows messages itself.

Now, we know that this class creates an instance of the former class, and that whenever an event is detected, it is reported back to the main class through the TriggerEvents method. This is not a clean OOP approach, but there was no point in making things more complicated.

This class has two properties defined: Enabled and AsynchronousEvents. The Enabled property is self explanatory, is handles enabling or disabling the message trapping. This is done with the helper class. When we want messages to be trapped we assign the handle to the NativeWindow descendant, and the WndProc method will be invoked whenever there is a message either broadcasted or dispatched, the handle will be released when the property is unset. This approach is better than controlling the property value in the WndProc method (the property is still evaluated on the method as a sanity check anyway), because the class won’t overload the system with unnecessary checks.

AsynchronousEvents controls the way events are invoked. If it is set, then the event will be called asynchronously, and WndProc won’t stall waiting for the application to process whatever it has to. Now, the way this is done on the TriggerEvents method is not peaceful. Many of you will criticize the BeginInvoke without following the design pattern. It is an unsafe option, but still it works if it only evolves calling thread safe code. Either way, I assume that you know what you are doing if you set this property.

There is a platform invoke to an API function called QueryDosDevice. This is a function that enables the translation between the drive letter, or DOS device name, to the full device path. This is used by one of two methods which translate the bit vector that was mentioned before. MaskToLogicalPaths translates the bit vector to a comma delimited string with all the drive letters described by the bit vector, MaskToDevicePaths on the other hand returns a string which is a list of the full device paths.

Two events are defined, OnVolumeInserted and OnVolumeRemoved. Both of them take the issued bit vector as a parameter.

Finally, I have implemented the IDisposable interface, I followed the design pattern, so there is not much to say here.

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

About the Author

Rui Reis
Portugal Portugal
Member
No Biography provided

Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
You must Sign In to use this message board.
Search this forum  
    Spacing  Noise  Layout  Per page   
AnswerRe: No message triggered on SD card insertion/removal?membermaurice_chavez26 Jan '09 - 10:14 
I have had same problem... try this.
 
#include <shlobj.h>
// Global declarations
#define WM_MEDIA_CHANGE (WM_USER + 666)
SHChangeNotifyEntry shcne;
ULONG hNotify;
 
struct SHNOTIFYSTRUCT
{
    ITEMIDLIST *dwItem1;
    ITEMIDLIST *dwItem2;
};
...
// On create
shcne.pidl = NULL;
shcne.fRecursive = TRUE;
 
hNotify = SHChangeNotifyRegister(hWnd, SHCNE_DISKEVENTS,
                        SHCNE_MEDIAREMOVED | SHCNE_MEDIAINSERTED,
                        WM_MEDIA_CHANGE, 1, &shcne);
 
...
// And in WindowProc of window (hWnd)
...
    if(uMsg == WM_MEDIA_CHANGE)
    {
        SHNOTIFYSTRUCT *shns = (SHNOTIFYSTRUCT *)wParam;
 
        switch(lParam)
        {
            case SHCNE_MEDIAINSERTED:        // media inserted event
                SHGetPathFromIDList(shns->dwItem1, buffer);
               // In buffer there are inserted media path i.e. E:\
            break;
 
            case SHCNE_MEDIAREMOVED:        // media removed event
                SHGetPathFromIDList(shns->dwItem1, buffer);
                // In buffer there are removed media path i.e. F:\
            break;
        }
    }
...
// On destroy
SHChangeNotifyDeregister(hNotify);
</shlobj.h>
And you should link program with shell32.lib.
GeneralRe: No message triggered on SD card insertion/removal?memberWolfeeCat7 Mar '09 - 6:14 
This is great! Thank you for sharing this!
QuestionAny VB.NET Port?memberhoriyip11 Jul '07 - 6:42 
This is very useful. However, I don't know C#. Has anyone done a VB.NET port?
 
Thank you.
QuestionDrive letter not show on media insertion ... Only on removal?memberMatt U.15 Feb '07 - 18:09 
I just downloaded the source code and read the article. I'm working on a project for a friend of mine. I've read the messages about detecting a USB device, and that's what I needed.
 
But, using the UNmodified source code, when I insert a CD into my CD-ROM drive, it just says "Volume inserted in ", but when I remove the CD it says "Volume removed from E:", and E: is, of course, my CD-ROM drive. Why is this? I'm on Win2K Pro SP4.
GeneralWM_CHANGEDEVICE Typmemberpherthyl17 Jan '07 - 15:57 
Just pointing out that you write WM_CHANGEDEVICE instead of WM_DEVICECHANGE at several points in your article. I guess I shouldn't have copied and pasted it Wink | ;)
Questionfaster method ?membervincent3121 Nov '06 - 8:55 
hello if filter methos faster wndprod for detect new device ?
 
thanks
 
Vincent
 

QuestionDoing this in a controlmemberthisIsReallyStupid12 Sep '06 - 9:18 
You mention that we can do this by overriding WndProc in a control or do it with NativeWindow like you did. Since my custom control is obviously not a top level window, it doesn't receive WM_DEVICECHANGE messages. How do I go about handling them then?
AnswerRe: Doing this in a controlmemberjkersch7 Dec '06 - 6:41 
yeah, i want to know that too.
i have several controls in my app and one of them needs to test if usb devices get pluggin in. how can i reveice the messages from a control?
do i have to call RegisterDeviceNotification() or is there a more elegant way?
Generaland with a windows servicememberIngo Fischer12 Dec '05 - 3:15 
how can I detect a USB-Device within a windows-service in c#?
I cannot override the WndProc - Method ( can I ? )
thanks a lot

GeneralRe: and with a windows servicemember ThatsAlok 21 Dec '09 - 0:57 
Ingo Fischer wrote:
I cannot override the WndProc - Method ( can I ? )

 
You can, if you service host a window or subscribe to window message handller
 

"Opinions are neither right nor wrong. I cannot change your opinion. I can, however, change what influences your opinion." - David Crow
Never mind - my own stupidity is the source of every "problem" - Mixture

cheers,
Alok Gupta
VC Forum Q&A :- I/IV
Support CRY- Child Relief and You

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Permalink | Advertise | Privacy | Mobile
Web02 | 2.6.130523.1 | Last Updated 12 Apr 2003
Article Copyright 2003 by Rui Reis
Everything else Copyright © CodeProject, 1999-2013
Terms of Use
Layout: fixed | fluid