Tip / Sign in to post questions, reply, level up, and achieve exciting badges. Know more

cross mob

Plug n Play Detection when using CYAPI.lib

lock attach
Attachments are accessible only for community members.

Plug n Play Detection when using CYAPI.lib

Anonymous
Not applicable
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++.

Attachments
0 Likes
379 Views
Contributors