os_read.hEvent = CreateEvent( NULL, // no security
TRUE, // explicit reset req
FALSE, // initial event reset
NULL ) ; // no name
if (os_read.hEvent == NULL) return -1;
// only try to read number of bytes in queue
ClearCommError( hCom, &dwErrorFlags, &ComStat ) ;
if(!ReadFile( hCom, lpszBlock, nMaxLength, &dwLength, &os_read)) {
if (GetLastError() == ERROR_IO_PENDING) {
// We have to wait for read to complete.
// This function will timeout according to the
// CommTimeOuts.ReadTotalTimeoutConstant variable
// Every time it times out, check for port errors
while(!GetOverlappedResult( hCom, &os_read, &dwLength, TRUE )) {
if(GetLastError() != ERROR_IO_INCOMPLETE) {
ClearCommError( hCom, &dwErrorFlags, &ComStat ) ;
break;
}
}
}
else {
// some other error occurred
dwLength = -1 ;
ClearCommError( hCom, &dwErrorFlags, &ComStat ) ;
}
}
CloseHandle(os_read.hEvent);
return ( dwLength ) ;