dahall / Vanara

A set of .NET libraries for Windows implementing PInvoke calls to many native Windows APIs with supporting wrappers.
MIT License
1.75k stars 190 forks source link

CM_REGISTER_NOTIFICATION callback: Incomplete eventData.u.DeviceInstance.InstanceId #432

Closed luni64 closed 9 months ago

luni64 commented 9 months ago

I'm trying to detect USB device changes using CM_Register_Notification. While this works in principle, the reported eventData.u.DeviceInstance.InstanceId is shortened somehow. Not sure if this is a bug or if I'm doing something wrong. Here a test program:

using System.Diagnostics;
using Vanara.PInvoke;
using static Vanara.PInvoke.CfgMgr32;

internal class Program
{
    static SafeHCMNOTIFICATION? context;
    static Win32Error Notification(HCMNOTIFICATION notify, IntPtr context, CM_NOTIFY_ACTION action, in CM_NOTIFY_EVENT_DATA eventData, uint eventDataSize)
    {
        unsafe
        {
            fixed (char* p = eventData.u.DeviceInstance.InstanceId)
            {
                var instanceId = new string(p);
                Debug.WriteLine($"Notification for {instanceId}: {action}");
            }
        }
        return Win32Error.ERROR_SUCCESS;
    }

    private static void Main(string[] args)
    {
        CM_Register_Notification(CM_NOTIFY_FILTER.AllDevices, default, Notification, out context);
        while (true) ;
    }
}

Which correctly prints the VID but cuts of the PID of the devices

Notification for USB\VID_05E3&P翿: CM_NOTIFY_ACTION_DEVICEINSTANCEREMOVED
Notification for USB\VID_05E3&P翿: CM_NOTIFY_ACTION_DEVICEINSTANCEENUMERATED
Notification for USB\VID_05E3&P翿: CM_NOTIFY_ACTION_DEVICEINSTANCESTARTED
Notification for USB\VID_16C0&P翿: CM_NOTIFY_ACTION_DEVICEINSTANCEENUMERATED
Notification for USB\VID_16C0&P翿: CM_NOTIFY_ACTION_DEVICEINSTANCESTARTED
Notification for USB\VID_16C0&P翿: CM_NOTIFY_ACTION_DEVICEINSTANCEENUMERATED
Notification for USB\VID_16C0&P翿: CM_NOTIFY_ACTION_DEVICEINSTANCEENUMERATED
Notification for USB\VID_16C0&P翿: CM_NOTIFY_ACTION_DEVICEINSTANCESTARTED
Notification for USB\VID_0925&P翿: CM_NOTIFY_ACTION_DEVICEINSTANCEENUMERATED
Notification for USB\VID_0925&P翿: CM_NOTIFY_ACTION_DEVICEINSTANCESTARTED
dahall commented 9 months ago

See code in unit test for commit to see how I resolved the problem (had to use pointers).

luni64 commented 9 months ago

Works perfectly now. Thanks for the fix and the extremly useful library