0
votes

I'm making application that listens for device notifications(through WndProc, DBT_DEVICEREMOVECOMPLETE and DBT_DEVICEARRIVAL). When I process DBT_DEVICEARRIVAL in WndProc, I get device path from PDEV_BROADCAST_DEVICEINTERFACE structure. When I try to create device handle with that path, it succeeds.

HANDLE device_handle = CreateFile(device_path.c_str(),
        GENERIC_WRITE | GENERIC_READ,
        FILE_SHARE_WRITE | FILE_SHARE_READ | FILE_SHARE_DELETE,
        NULL,
        OPEN_EXISTING,
        0,
        NULL);

    if (device_handle == INVALID_HANDLE_VALUE)
        return false;

But when I handle DBT_DEVICEREMOVECOMPLETE, I do the same thing with PDEV_BROADCAST_DEVICEINTERFACE structure, and the path is same as in DBT_DEVICEARRIVAL, but CreateFile always returns INVALID_HANDLE_VALUE

The funniest thing is, when I try to execute in debug mode, creating device handle works normally, both from DBT_DEVICEARRIVAL and DBT_DEVICEREMOVECOMPLETE.

I would appreciate any help.

1
Doesn't the DBT_DEVICEREMOVECOMPLETE event imply that the device has been removed? If so I would expect an attempt to open the device that is no more to fail. - IInspectable
when DBT_DEVICEREMOVECOMPLETE come - device already removed and name not valid. so must be error file not found - RbMm
Thanks ! But is there a way to intercept removal and to get device path before device is removed ? - someguy
for what ? for what you need open device on removal, when device destroyed ? - RbMm
@someguy Can't you get that info from DBT_DEVICEQUERYREMOVE or DBT_DEVICEREMOVEPENDING? Why do you need to wait until the device has been completely removed from the system before getting its info? - Remy Lebeau

1 Answers

0
votes

It is improper to create handle when receiving DBT_DEVICEREMOVECOMPLETE message.

The system broadcasts the DBT_DEVICEREMOVECOMPLETE device event when a device or piece of media has been physically removed.

You can use RegisterDeviceNotification to receive more specific device event messages. There is a MSDN:sample.