Click here to Skip to main content
15,919,931 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I am trying to auto detect a USB serial port arrival/removal. I can detect any device change using the overloaded WndProc method but I need more information about the device.
It seems you can do this by using the LParam to point to a device structure, maybe, DEV_BROADCAST_HDR or other.

The event 'DBT_DEVTYP_PORT' does not seem to be the device type that is detected in my code, 'DBT_DEVTYP_DEVICEINTERFACE' is the one I am getting. My code below shows how far I have got. I am new to C# so please be patient.

protected override void WndProc(ref Message m)
    if (m.Msg == WM_DEVICE_CHANGE)
        switch (m.WParam.ToInt32())
            case DBT_DEVICE_ARRIVAL:
                DEV_BROADCAST_HDR hdr = (DEV_BROADCAST_HDR)m.GetLParam(typeof(DEV_BROADCAST_HDR));
                switch (hdr.DeviceType)
                    case DBT_DEVTYP_DEVICEINTERFACE:
                        string portName = Marshal.PtrToStringUni( (IntPtr)(m.LParam.ToInt32() + Marshal.SizeOf(typeof(DEV_BROADCAST_PORT_Fixed))) );
                        MessageBox.Show("Port '" + portName + "' arrived.");
    base.WndProc(ref m);

The code above gives me the GUID of the device detected but I need more information.

Any ideas?


I have done this with C++ but the messages and parameters can be handled similar with C#.

There will be specific messages for serial and parallel ports:

  • Check that LPARAM is not NULL
  • Check if the dbcp_devicetype member is DBT_DEVTYP_PORT
  • Check the dbcp_name member if it begins with 'COM'. It contains the serial port name as COMx.

The above messages are send with DBT_DEVICEARRIVAL and DBT_DEVICEREMOVECOMPLETE upon insertion / removal.

Use the detected serial port name to retrieve additional information about the serial port.
Share this answer
CPallini 15-Oct-15 6:11am    
Thanks for the reply.

1) LPARAM is not null and so there is data to point to.

2) As you can see LPARAM has been cast to DEV_BROADCAST_HDR which is just a structure to hold the data.

3) The device type is not 'DBT_DEVTYP_PORT', I get the value 5 which seems to be 'DBT_DEVTYP_DEVICEINTERFACE'.

I have debugged it to the device type and it does detect my USB serial device as stated earlier but I stuck here.
Share this answer
Philippe Mori 15-Oct-15 12:53pm    
This is not an anweer. You should add your comment to appropriate solution instead or update your question.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900