Plug n Play Detection when using CYAPI.lib

Question: How can we implement hot-plugging detection when using cyapi.lib?

 

Answer:

You can use the constructor for the CCyUSBDevice class to register for PnP events.

Here is an example,

void __fastcall TMainForm::FormCreate(TObject *Sender)
{
USBDevice = new CCyUSBDevice(Handle);
CurrentEndPt = USBDevice->ControlEndPt;
}
// Overload MainForm's WndProc method to watch for PnP messages
// Requires #include
void __fastcall TMainForm::WndProc(TMessage &Message)
{
if (Message.Msg == WM_DEVICECHANGE) {
// Tracks DBT_DEVICEARRIVAL followed by DBT_DEVNODES_CHANGED
if (Message.WParam == DBT_DEVICEARRIVAL) {
bPnP_Arrival = true;
bPnP_DevNodeChange = false;
}

// Tracks DBT_DEVNODES_CHANGED followed by DBT_DEVICEREMOVECOMPLETE

if (Message.WParam == DBT_DEVNODES_CHANGED) {
bPnP_DevNodeChange = true;
bPnP_Removal = false;
}
if (Message.WParam == DBT_DEVICEREMOVECOMPLETE) {
bPnP_Removal = true;
PDEV_BROADCAST_HDR bcastHdr = (PDEV_BROADCAST_HDR) Message.LParam;
if (bcastHdr->dbch_devicetype == DBT_DEVTYP_HANDLE) {
PDEV_BROADCAST_HANDLE pDev = (PDEV_BROADCAST_HANDLE) Message.LParam;
if (pDev->dbch_handle == USBDevice->DeviceHandle())
USBDevice->Close();

}

}

// If DBT_DEVNODES_CHANGED followed by DBT_DEVICEREMOVECOMPLETE

if (bPnP_Removal && bPnP_DevNodeChange) {
Sleep(10);
DisplayDevices();
bPnP_Removal = false;
bPnP_DevNodeChange = false;
}

 

// If DBT_DEVICEARRIVAL followed by DBT_DEVNODES_CHANGED

if (bPnP_DevNodeChange && bPnP_Arrival) {
DisplayDevices();
bPnP_Arrival = false;
bPnP_DevNodeChange = false;
}

}
TForm::WndProc(Message);
}

To more about this implementation please go through the attached CYAPI programmer's reference which contains a number of code example in VC++.