Opening LPT port in C++

  • Thread starter Thread starter CeZaR
  • Start date Start date
C

CeZaR

Hi,
I've posted earlier a question regarding the call to GetCommState.
Here is the code for the function.
The problem is that GetCommState always returns false!!
Why?

void Open()
{
// the DCB and COMMTIMEOUTS structure are declare a __value struct
DCB *dcbCommPort = __nogc new DCB();
COMMTIMEOUTS *ctoCommPort = __nogc new COMMTIMEOUTS();
// OPEN THE COMM PORT.
hComm = CreateFile("LPT1",GENERIC_READ | GENERIC_WRITE,0, 0,OPEN_EXISTING,0,0);
// IF THE PORT CANNOT BE OPENED, BAIL OUT.
if(hComm == INVALID_HANDLE_VALUE)
{
throw(new ApplicationException("Comm Port Can Not Be Opened"));
}
// SET THE COMM TIMEOUTS.
GetCommTimeouts(hComm,ctoCommPort);
ctoCommPort->ReadTotalTimeoutConstant = ReadTimeout;
ctoCommPort->ReadTotalTimeoutMultiplier = 0;
ctoCommPort->WriteTotalTimeoutMultiplier = 0;
ctoCommPort->WriteTotalTimeoutConstant = 0;
SetCommTimeouts(hComm,ctoCommPort);

// SET BAUD RATE, PARITY, WORD SIZE, AND STOP BITS.
GetCommState(hComm, dcbCommPort);
dcbCommPort->BaudRate=BaudRate;
dcbCommPort->flags=0;
//dcb.fBinary=1;
dcbCommPort->flags|=1;
if (Parity>0)
{
dcbCommPort->flags|=2;
}
dcbCommPort->Parity=Parity;
dcbCommPort->ByteSize=ByteSize;
dcbCommPort->StopBits=StopBits;
if (!SetCommState(hComm, dcbCommPort)) // always returns false
{
throw(new ApplicationException("Comm Port Can Not Be Opened"));
}
Opened = true;
}

Thanks!
 
CeZaR said:
I've posted earlier a question regarding the call to GetCommState.
Here is the code for the function.
The problem is that GetCommState always returns false!!

You shouldn't have to guess. _Immediately_ after the function returns, call
GetLastError().

Now, I haven't researched it, but if IJW is trampling on the thread's last
Win32 error by making some intervening Win32 API call, take a look at this:

http://blogs.msdn.com/adam_nathan/archive/2003/04/25/56643.aspx

Just by the way, is the LPT port in question controlled by a printer driver?

Regards,
Will
 
I've stopped the spooler service before running the program.
Then i call CreateFile with "\\\\.\\NONSPOOLED_LPT1".
BTW GetLastError returns 2 -> Invalid function.
 
And, finally i've fixed it!
The LPT port doesn't support all of the function in this code.
They all work for COM ports.
For LPT use just CreateFile, WriteFile.
 
Back
Top