由于 USB-Com 移除而出现的异常非常烦人。所以我建议消除他们的大部分原因。
您必须处理 Windows 消息 WM_DEVICECHANGE 并检测端口删除。然后设置特殊标志,不要对带有此标志的端口进行任何操作!如果再次插入 USB-Com,则重新初始化串行端口。一些帮助的代码:
const
DBT_DEVICEARRIVAL = $8000;
DBT_DEVICEREMOVECOMPLETE = $8004;
DBT_DEVICEQUERYREMOVE = $8001;
DBT_DEVTYP_PORT = 3;
type
PDevBroadcastHdr = ^TDevBroadcastHdr;
TDevBroadcastHdr = packed record
dbcd_size: DWORD;
dbcd_devicetype: DWORD;
dbcd_reserved: DWORD;
end;
PDEV_BROADCAST_PORT = ^TDEV_BROADCAST_PORT;
TDEV_BROADCAST_PORT = packed record
dbcp_size: DWord;
dbcp_devicetype: DWord;
dbcp_reserved: DWord;
dbcp_name: array[0..MAX_PATH] of Char;
end;
...
procedure WMDEVICECHANGE(var Msg: TMessage); message WM_DEVICECHANGE;
...
procedure TForm1.WMDEVICECHANGE(var Msg: TMessage);
var
prt: PDEV_BROADCAST_PORT;
s: string;
begin
if Msg.wparam = DBT_DEVICEREMOVECOMPLETE then
if PDevBroadcastHdr(Msg.lParam)^.dbcd_devicetype = DBT_DEVTYP_PORT then
begin
b_PortRemoved := True; //check this flag before each operation with port.
prt := PDEV_BROADCAST_PORT(PDEV_BROADCAST_PORT(Msg.lParam));
s := prt.dbcp_name;
ShowMessage('ComPort ' + s + ' has been removed. What can I do?');
end;
if Msg.wparam = DBT_DEVICEARRIVAL then
if PDevBroadcastHdr(Msg.lParam)^.dbcd_devicetype = DBT_DEVTYP_PORT then begin
// USB-COM plugged, you can find it and make some reinitialisation
end;
end;