Here is some code which simply opens a com port and should allow me to do things with it, however it does not because the COM port returns with "Access Denied" as you can see I am trying to do everything to clear up that message for the next run in order to free up the port to no avail. The port remains frozen if some error occurs.... any idea how to free up a port, restart it or something in order to regain access to the port after an error has occurred without needing to unplug, replug it? thanks for your help!
DCB dcb;
b->h1 = CreateFile(b->port,GENERIC_READ | GENERIC_WRITE,
0, NULL, OPEN_EXISTING, 0, NULL);
if (b->h1 == INVALID_HANDLE_VALUE)
{
DWORD MsgID = GetLastError();
char *TextSize;
FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, 0, MsgID, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),(LPTSTR) &TextSize, 0, 0);
DWORD dwErrorFlags;
COMSTAT ComStat;
int result;
BOOL fSuccess2;
ClearCommError(b->h1, &dwErrorFlags, &ComStat );
ClearCommBreak(b->h1);
dcb.BaudRate = b->boud; dcb.ByteSize = 8; dcb.Parity = NOPARITY; dcb.StopBits = ONESTOPBIT; SetCommState(b->h1, &dcb);
fSuccess2 = SetCommState(b->h1, &dcb);
PurgeComm(b->h1, PURGE_TXABORT | PURGE_RXABORT | PURGE_TXCLEAR | PURGE_RXCLEAR);
CloseHandle(b->h1);
b->h1 = NULL;
b = NULL;
a = NULL;
hSock = NULL;
hSock2 = NULL;
ComSock.Close();
ClosePort();
return 2;
}
[EDIT Jochen Arndt: Copied from solution]
The idea is to be able to "Force" close the port, the problem is another thread may have the port open and I want to close it, without having access to the other instance that encountered an error.
For example, someone might pull out the chord during transmission, if we encounter the error, now we want to clear up the port, so everything would be fine on the next run, I am specifically interested in these functions as they seem to help with this process but they didnt do much to resolve the "Access Denied" error:
ClearCommError(b->h1, &dwErrorFlags, &ComStat );
ClearCommBreak(b->h1);
PurgeComm(b->h1, PURGE_TXABORT | PURGE_RXABORT | PURGE_TXCLEAR | PURGE_RXCLEAR);
Another option I looked at while investigating was the use of DevCon.exe which is not what I am looking for, I am specifically looking to restart the com port using code, not plugging in & unplugging the device, etc....
Thanks for your help & advice!