WriteFile to LPT behaves strange

S

Sergey

Hi, everybody,

I want to send a short sequence of bytes to the printer, connected via
LPT port. Below you can find my sample code.
In this particular sample synchronous WriteFile succeeds, but the
printer does not receive data immediately. It receives data only after
CloseHandle has been called. I can see that in debugger and in the in the
dump made by the printer.
In case when instead of dwWritten WriteFile accepts some bigger value
(like 128, 512, 1024), the data will be sent to the printer immediately
after a call to WriteFile (that's what I need), but by bytes (one by one)
with huge second delays. By asynchronous WriteFile calls the same phenomenon
persists.
It seems that the issue is caused by wrong buffering mode or incorrectly
set port timeouts, but I have tried to set different buffering mode flags in
CreateFile call and even aligned the buffer. SetCommTimeouts and similar API
calls fail with "Invalid function" for LPT port.
Thus, either to call CloseHandle() in order to send bytes to the printer
or send them one by one specifying bigger buffer size. Both are unacceptable
for me.
Where is my mistake and how can I send short bytes sequence to the LPT
printer?

Thank you.


HANDLE hDirect;
DWORD dwWritten, dwRead, dwCmdLen;
char szPjlCmd[] = "\x1b%-12345X@PJL\r\n@PJL INFO ID\r\n\x1b%-12345X";
char* pszOutput;
char szInput[1024];
dwCmdLen = (_tcslen(szPjlCmd)+1)*sizeof(char);
pszOutput = (char*) VirtualAlloc(NULL,512,MEM_COMMIT,PAGE_READWRITE);
strcpy(pszOutput,szPjlCmd);
hDirect = CreateFile("LPT1",
GENERIC_READ | GENERIC_WRITE,
//FILE_SHARE_READ | FILE_SHARE_WRITE,
0,
NULL,
OPEN_EXISTING,
//FILE_FLAG_OVERLAPPED,
//FILE_FLAG_NO_BUFFERING,
//FILE_FLAG_WRITE_THROUGH | FILE_FLAG_NO_BUFFERING,
0,
NULL);
if(hDirect == INVALID_HANDLE_VALUE)
{
OUTPUT_SYSTEM_ERROR()
return -1;
}
dwWritten = (_tcslen(szPjlCmd)+1)*sizeof(TCHAR);
if(WriteFile(hDirect,
pszOutput,
dwWritten,
&dwWritten,
NULL) == 0)
{
OUTPUT_SYSTEM_ERROR()
return -2;
}

CloseHandle(hDirect);
VirtualFree(
pszOutput,
0,
MEM_RELEASE);
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top