// for RegisterDeviceNotification

// This code is NOT used in this executable.
// It is provided for information only!

// This code shows ONE way in which your executable could be informed when a
//  USB P&P device is inserted or removed.
// It provides a signal that the USB system has detected the addition/removal
// of USB P&P device BUT does NOT tell you which device.

#include "project.h"

#include <cfgmgr32.h>
#include <initguid.h>
#include <usbiodef.h>
#pragma comment(lib, "Cfgmgr32.lib")

// I have NOT implemented a function to DO anything specific when
// a USB PnP device is added/removed,
// But for reference I have provided a minimal generic function
// to report that a related action has occurred.



int usb_device_changed = 1;

static DWORD  my_CM_NOTIFY_CALLBACK (
_In_ HCMNOTIFICATION       hNotify,
_In_opt_ PVOID             Context,
_In_ CM_NOTIFY_ACTION      Action,
_In_reads_bytes_(EventDataSize) PCM_NOTIFY_EVENT_DATA EventData,
_In_ DWORD                 EventDataSize
)

{
    switch (Action)
    {
        case CM_NOTIFY_ACTION_DEVICEINTERFACEARRIVAL:
            addText((TCHAR*) _TEXT("USB PnP device added\n")); addText(txtBuffer);

            usb_device_changed = 1;
            break;

        case CM_NOTIFY_ACTION_DEVICEINTERFACEREMOVAL:
            addText((TCHAR*)_TEXT("USB PnP device removed\n")); addText(txtBuffer);
            usb_device_changed = 1;
            break;
    }

    return   ERROR_SUCCESS;
}

void usb_CM_Register_Notification()
{
    HCMNOTIFICATION myNotifyHandle;

    char cont[128] = { 0 };
    CM_NOTIFY_FILTER NotifyFilter = { 0 };
    NotifyFilter.cbSize = sizeof(NotifyFilter);
    NotifyFilter.FilterType = CM_NOTIFY_FILTER_TYPE_DEVICEINTERFACE;
    NotifyFilter.u.DeviceInterface.ClassGuid = GUID_DEVINTERFACE_USB_DEVICE;

    CM_Register_Notification
    ( &NotifyFilter
    , &cont
    , &my_CM_NOTIFY_CALLBACK
    , &myNotifyHandle
    )   ;

}
