WriteFile doesn't send data to LPT1 until CloseHandle is called

Greetings groups.
Please, forgive me for posting twice, didn't really know where this
question should really go to, nor where could I get an answer.

My program tries to send data directly to the parallel port to a
printer, code lies at the end. In short it does this:

First opens with CreateFile the device "\\.\\LPT1" as read/write in a
non-overlapped mode, next sends a string to the printer on the other
side, finally waits for the user to enter any string to close handle
and quit.

I've noted with the aid of sniffers (http://www.sysinternals.com) that
WriteFile doesn't really send anything to the port until
CloseHandle(hPort) is called, then the full comunication is done.

I've tried to force windows to send the bytes immediately with
TransmitCommChar, but the function returns with an error and no char
is send, whatsoever. If I call FlushBuffer(hPort) I don't get anything
send to the port, either, until the handle is closed.

Can anyone help me? How can I force Windows to dispatch the info.
immediately? Am I doing something wrong?

I'm working with win2000 and compiling with Visual C++ 6.0

Something else: would it be too much asking you benevolent souls
to answer with a copy to my e-mail? I read news through google, and
sometimes it gets difficult to see thru the threads over there.

Thank you!!!
Sincerely
Battle Troll
-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*

// ReadWriteLPT1.cpp : Tries to read and write directly to the
parallel port
//
#include<stdio.h>
#include<windows.h>

typedef struct _ComandoESCP2 {
   char *Nombre;
   unsigned int LongitudTotal;
   char *Secuencia;
   unsigned int CaracteresFijos;
}ComandoESCP2;

//#define TEMP_FILE "hay.txt"
#define MAX_STRING_SIZE   255

enum INDICES_COMANDOS { EXIT_PACKET_MODE, INITIALIZE_PRINTER };

ComandoESCP2 Epson_C43[] = {
   {"Exit Packet Mode", 27,
"\x00\x00\x00\x1B\x01\x40\x45\x4A\x4C\x20\x31\x32\x38\x34\x2E\x34\x0A\x40\x45\x4A\x4C\x20\x20\x20\x20\x20\x0A",
27 },
   {"Initialize Printer", 2, "\x1B\x40", 2 }
};

int main(int argc, char* argv[])
{
	DCB dcb;
	COMMTIMEOUTS timeout;
	HANDLE hPort;
	BOOL fSuccess;
	char *pcCommPort = "\\\\.\\LPT1"; //"LPT1"; //theoretically it's the
same to call it under one name or the other
	char StringBuffer[MAX_STRING_SIZE ]="";

	DWORD BytesEscritos=0;
	BOOL FinalAlcanzado=1;

	printf( "%s", "Trying to open the port...\n");	
	hPort = CreateFile( pcCommPort, //"\\\\.\\LPT1", 
//"\\\\.\\NONSPOOLED_LPT1", //it also works with the latter
                    GENERIC_READ | GENERIC_WRITE,
                    0,    // (fixed parameter) must be opened with
exclusive-access
                    NULL, // no security attributes
                    OPEN_EXISTING, //(fixed parameter)  must use
OPEN_EXISTING
                    FILE_FLAG_OVERLAPPED | FILE_FLAG_NO_BUFFERING,
//FILE_ATTRIBUTE_NORMAL,
                    NULL  // (fixed parameter) hTemplate must be NULL
for comm devices
                    );

   if (hPort == INVALID_HANDLE_VALUE) 
   {
       // Handle the error.
	   printf ("Imposible to open the port %s exclusively for
read/write\n", pcCommPort );
       printf ("CreateFile failed returning %d.\n", GetLastError());
       return 1;
   }
	printf( "%s", "Port succesfully opened\n");

   //-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*

	//primero trataremos de sacarla del modo de paquetes
	printf( "%s", "Trying to get printer out of packet mode...\n");

   fSuccess = WriteFile( hPort,					//File Handle (to a port in this
case)
		   Epson_C43[EXIT_PACKET_MODE].Secuencia,	//Data to be written
		   Epson_C43[EXIT_PACKET_MODE].CaracteresFijos,	//Number of bytes to
be written
		   &BytesEscritos,	//Output bytes send
		   NULL );//&o );	//Overlapping buffer 
	
   if( !fSuccess)
   {
	   //fclose(Entrada);   	   
	   printf( "Couldn't write at the port:\n", pcCommPort );
	   printf( "To the most: %u bytes were written\n", BytesEscritos );

	   printf( "%s", "\nEnter a string plus <ENTER> to quit...\n");
	   scanf("%s", StringBuffer);

	   CloseHandle( hPort);
	   return 4;
   } 
	
   printf( "%s", "Printer out of packet mode\n");
   printf( "Printed: %i chars (should've been %i)\n",
BytesEscritos,	Epson_C43[EXIT_PACKET_MODE].CaracteresFijos );

   printf( "%s", "\nEnter a string plus <ENTER> to quit...\n");
   scanf("%s", StringBuffer);
   CloseHandle( hPort);

   return 0;
}
0
6/16/2004 1:05:32 AM
vc.mfc 33608 articles. 0 followers. Follow

7 Replies
776 Views

Similar Articles

[PageSpeed] 9

On Tue, 15 Jun 2004 18:05:32 -0700, Battle Troll wrote:

> Greetings groups.
> Please, forgive me for posting twice, didn't really know where this
> question should really go to, nor where could I get an answer.
> 
> My program tries to send data directly to the parallel port to a
> printer, code lies at the end. In short it does this:
> 
> First opens with CreateFile the device "\\.\\LPT1" as read/write in a
> non-overlapped mode, next sends a string to the printer on the other
> side, finally waits for the user to enter any string to close handle
> and quit.
[snip]

These are buffered I/O routines. Call FlushFileBuffers (HANDLE) after
your write.

-- 

Quidquid latine dictum sit, altum viditur.


0
me7986 (249)
6/16/2004 12:53:16 PM
antoniopineda@att.net.mx (Battle Troll) wrote:

> My program tries to send data directly to the parallel port to a
> printer, code lies at the end...

I don't know why WriteFile, etc. are not working properly, but try
OpenPrinter, StartDocPrinter, WritePrinter and EndDocPrinter instead.
I have used these to send plain ASCII data to an Epson LX-300+ printer
connected to LPT1:.
0
6/16/2004 3:40:56 PM
Jim <me@privacy.net> wrote in message news:<pan.2004.06.16.12.53.13.
> These are buffered I/O routines. Call FlushFileBuffers (HANDLE) after
> your write.

Greetings Jim, thanks for answering.
I've already done so, once I placed right after WriteFile(hPort,
String[], etc.) a FlushFileBuffers( hPort) sentence - with no results,
the sniffer shows no data has actually been sent to the parallel port
(did you read the complete post). The sniffer is software, but a group
of probe LED's on the parallel port pins also show no voltages are
sent phisically, either, until CloseHandle(hPort).

Most amazing of all, this happens just with windows 2000, I've just
tried my program in windows 98 and the data is sent automatically,
without any need of a FlushFileBuffers, I don't have a winXP or winME
machine at hand, to do more testing. However, I'm starting to think in
win2k the management of the ports has changed somehow...

Can someone test the code in winXP, or winME, please? I'd very much
like to hear what happens... testing on more w2k machines could be
helpful, too - perhaps the printer driving is conflicting - maybe I
should uninstall it first, perhaps a background process is sensing
periodically the par.port and interferring the communication...
perhaps it's God himself showing his power... who knows?
0
6/16/2004 6:33:19 PM
johnbrown105@hotmail.com (John Brown) wrote:

>antoniopineda@att.net.mx (Battle Troll) wrote:
>
>> My program tries to send data directly to the parallel port to a
>> printer, code lies at the end...
>
>I don't know why WriteFile, etc. are not working properly, but try
>OpenPrinter, StartDocPrinter, WritePrinter and EndDocPrinter instead.
>I have used these to send plain ASCII data to an Epson LX-300+ printer
>connected to LPT1:.

I had exactly this problem with XP and WriteFile. The reason may not
fit your situation exactly, but I found it very interesting and it may
give you some clues.

XP, as opposed to 9.x, performs these operations (in my case on a
serial port) in strict logical order. So, for instance, if you change
the baudrate when there is a ReadFile outstanding, then use WriteFile,
it waits to complete the read at the original baudrate before changing
and performing the write. (With 9.x you got the baud change when you
asked for it, and screwed any current operation).

Now if nothing turns up for the outstanding read, and it is set on a
long timeout, then you have a deadlock. Closing the port then kills
the read, but the write gets through before the close is performed.

0
colin8390 (10)
6/16/2004 7:09:15 PM
John:
Thanks for your comment.

Unfortunately, I cannot use OpenPrinter, etc. My main interest is not
just sending data to the printer to be printed, which could be
achieved through a lot of ways.

I want to send printer commands to the LPT1 and immediately afterwards
read the answer the printer gives back, that way i'll be able to get
printer name, manufacturer, ink levels, etc. given the appropriate
commands.

Even if my problems with WriteFile got solved, I still have to solve
how to read from the parallel port, for info. is contradictory but
most docs. i've read state that you cannot read data from par. port
with ReadFile... how can I, then?

I think I'm going to open a new thread with this question as
subject...
thanks anyway
0
6/17/2004 12:19:37 AM
antoniopineda@att.net.mx (Battle Troll) wrote:

> Can someone test the code in winXP, or winME, please? 

Windows Server 2003 (for Small Business Server)- data printed right away
Windows XP SP1 - did not print until CloseHandle
Windows 2000 Server SP4 - Did not print until CloseHandle
Windows 2000 Professional SP4 - Did not print until CloseHandle
0
6/17/2004 12:19:51 AM
On 16 Jun 2004 17:19:37 -0700, antoniopineda@att.net.mx (Battle Troll)
wrote:

>John:
>Thanks for your comment.
>
>Unfortunately, I cannot use OpenPrinter, etc. My main interest is not
>just sending data to the printer to be printed, which could be
>achieved through a lot of ways.
>
>I want to send printer commands to the LPT1 and immediately afterwards
>read the answer the printer gives back, that way i'll be able to get
>printer name, manufacturer, ink levels, etc. given the appropriate
>commands.
>
>Even if my problems with WriteFile got solved, I still have to solve
>how to read from the parallel port, for info. is contradictory but
>most docs. i've read state that you cannot read data from par. port
>with ReadFile... how can I, then?
>
>I think I'm going to open a new thread with this question as
>subject...
>thanks anyway

Try "Parallel Port Central" at http://www.lvr.com/parport.htm.
They might have a solution for you. 


0
r
6/17/2004 12:33:21 AM
Reply:

Similar Artilces:

Can't send mail
Hi, Is there some kind of secret about sending mail? I haven't been able to figure out how to send emails with any of my different accounts with outlook. I can recieve them just fine but I can't send any. What configurations do I need? Thanks! Allstarpballer What version of Outlook do you have? What sort of account(s)? Do you get any error messages when you try to send? -- Jeff Stephenson Outlook Development This posting is provided "AS IS" with no warranties, and confers no rights "Allstarpballer" <gamgeek@allstarpball.com> wrote in mess...

sending email
New to outlook, Once I have composed my message and try to send, outlook will not send. I save the email and when I go back to my inbox I find the message as not yet sent. It will send at this point when I select send. Why can't I send when I first create the message? What do you mean when you say it will not send. Do you get an error? Ray at work "Marc" <anonymous@discussions.microsoft.com> wrote in message news:039101c39da1$dcad0d50$a501280a@phx.gbl... > New to outlook, > > Once I have composed my message and try to send, outlook > will not send. I ...

problem sending invitations in Outlook Client
Only 1 user (that we know of) has this problem, with all others it works perfectly: - If he creates a meeting in Outlook, everything works fine - If he creates an appointment using the CRM Outlook Bar, the following error occurs when she invites someone else: (translated from Dutch) ----------------------------------------------------------- From: System Manager Sent: [Date] To: [User with the problem] Subject: Undeliverable: [Customer Name] Your message has not reached a or any of your addressees. The following recipient(s) could not be reached: [User with problem] on [date] ...

Outlook 2003 won't Send or Receive
WindowsXP\Outlook 2003 Last night when I opened Outlook 2003....Windows opened showing Processing failed and asking me to enter my ID and Password. This Window showed my email providers name (Comcast.Com)...and my user and Password (password in X's) were populated. I however re-entered my ID\password...same message appeared. I have NOT added\deleted or changed anything in my PC to include changes, etc, in Outlook. I have an Internet Connection, I can open a browser and go to Websites.....Comcast is not showing any email issues at their website..... Suggestions as to...

WriteFile
Hi , I am using WriteFile function for writting some data to harddisk. Is there any limit in size of data it can write. Basically this function is writting imcomplete data. I checked the contents of file. ( Writs encoded data to file then decode the data using Winzip ( MIME data ) no of Bytes are at boundries like : fff, 9fff, ffff ... Any idea why this is hapening ? I'm not sure if there is a limit, or how to find out. Are you checking the parameter that tells the number of bytes written to see if it equals the number of bytes to write? Perhaps you can just keep calling WriteFile...

Application Data
On my old computer with Outlook express I could goto Windows>Application Data and delete stored files to save room on the drive. I cannot find this on XP and using the full outlook. If anyone could help please email the above addy. Thanks in advance Open Windows Explorer and configure it to show you all hidden/system files. (Select Tools | Folder Options | View tab) "Tres" <tres1013@msn.com> wrote in message news:00c001c35009$b93630d0$a001280a@phx.gbl... > On my old computer with Outlook express I could goto > > Windows>Application Data and delete stored...

compare a list of data and have it listed from least to greatest in another column
This is my first post here so bare with me. I need help with a report I'm making. Each month we gather data on safety items. We track which items are safe and which are at risk. From these 2 numbers I calculate the percentage each item is being done safe. example: Item |Safe|At Risk|% Safe Gloves | 10 | 5 | 50.00% The report is on one sheet in the workbook and the data I enter is on another. The calculations are made on the data sheet and then linked to the report sheet. There are 40 items that we track. On the bottom of the report is a place we put the top 5 at risk items. This is t...

Empty outbox
My outbox is empty but outlook tries to send a message anyway. I get an error message: Task 'postoffice.pacbell.net - Sending' reported error (0x8004210B) : 'The operation timed out waiting for a response from the sending (SMTP) server. If you continue to receive this message, contact your server administrator or Internet service provider (ISP).' I removed my default mail account and got the same error on the alternate account. Scanpst showed errors which it fixed. The problem remains. Running scanpst shows no error now. Removed and reinstalled AVG email plugin with no...

Find new data in one Table
Dear all, I have two tables, the first is like a cadastre of products... the second is the movement of stock. I update the second table (movement of stock) with an excel sheet and this sheet can contain some new product_code. These new codes don't exist in the first table - cadastre of products... How can I find the product codes that exist in the second table and don't exist in the first table? The two tables don't have primary key, only a relation whith the field product_code. Thanks a lot!!! Andr=E9. ...

Any way to default to "Send now" instead of "Edit before sending"?
When responding to a meeting request in Outlook 2007, is there a way to make it default to "Send the response now" instead of "Edit the response before sending"? RNW;118796 Wrote: > When responding to a meeting request in Outlook 2007, is there a way to > make > it default to "Send the response now" instead of "Edit the response > before > sending"? I don't believe it's possible to modify that. -- Brian Tillman [MVP-Outlook] http://forums.slipstick.com ...

Send Internal Mail Externally
I have a subsidiary that we connect to through a vpn tunnel. They are not a part of our Exchange organization. They use lotus notes for email. We are unable to telnet into their server and we believe that for some reason port 25 is being blocked internally. Is there any way to ensure that email to this subsidiary travels externally rather than internally? We are running Exchange 2003 sp2 on W2K3 server sp1. There is no lotus notes connector of any kind. All email directed to them is sitting in the queue. Any help would be appreciated. Thanks. CK ...

Cannot Send or Receive
Since this morning Ihave been unable to send or receive,checked all settings against my wifes identical laptop. I have also deleted and re-added. I receive -- An unknown error has occurred. Account: 'mail.comcast.net', Server: 'mail.comcast.net', Protocol: POP3, Port: 110, Secure(SSL): No, Error Number: 0x80004005 Any help would be greatley appreciated Dave Try this: In your browser go to http://www.comcast.net, then click the = Email button and log in.Then clean out all the folders in your webmail. If you = want to save any messages, create a new folder and mov...

CRM Mobile and sending Emails
When you're out on the road connecting by GPRS how do they send emails to clients that will be recorded in CRM? -- Regards Helen I don't believe this is possible. Your users will need to send the email via Outlook Mobile on their SmartPhone and then "Track in CRM" when they return to their computer. "Helen Smith" wrote: > When you're out on the road connecting by GPRS how do they send emails to > clients that will be recorded in CRM? > > -- > Regards > Helen ...

How do I change the order of the series in the Source Data?
I have a chart that trackes sales numbers by the month. Each year I add a series. I would like to get the series to display in order. How do I change the order? Select the series that you want to reorder. You will see something that looks like this: =SERIES(,'Sheet1'!$A$2:$A$11,'Sheet1!$H$2:$H$11,5) You need to change the # at the very end of the series. =SERIES(,'Sheet1'!$A$2:$A$11,'Sheet1!$H$2:$H$11,1) "Earl" <Earl@discussions.microsoft.com> wrote in message news:1E8EF0FE-4E7C-4773-A379-99EB39EA829B@microsoft.com... > I have a chart that ...

How do I send and recieve through my other email to outlook?
I cant figure out how to set up my email to go through outlook from my outside account. I'm guessing that you're trying to use Outlook to connect to an external mail server. Does the firewall in your office allow those type of connections? "Toni-Ann" <Toni-Ann@discussions.microsoft.com> wrote in message news:7D5A2B19-9348-4C02-8E49-B0C4398942C1@microsoft.com... >I cant figure out how to set up my email to go through outlook from my > outside account. Yes "Vince Averello [MVP-Outlook]" wrote: > I'm guessing that you're trying to use ...

Filter Form to get a data relating to a date field
I have created a continuous form within an Internal Audit database and want to be able to filter by a From and To Date range and a name. I have set it up and at the back entered the following code to the Apply Filter button but I keep getting "Variable not Defined". I have tried lots of things but cannot sort it. Any suggestions? I have put a note of the code used below. Private Sub Command9_Click() Me.Filter = "1=1" 'Response Due Date If Not IsNull(Me.txtResponseDateFrom) Then Me.Filter = Me.Filter & " AND [Responseduebydate] ...

send email using template
I am trying to send some information from Access in an email and need some code to open a new outlook template to paste the information into. I have saved the template as an .oft file could you help me with the code and saved the Access information in a temporary word document Dim olApp As Outlook.Application Dim msMailItem As MailItem ' Create a new instance of Outlook Set olApp = New Outlook.Application ' Create a new mail item Set msMailItem = olApp.CreateItem(olMailItem) How do I specify a template please. And can I then copy and paste informa...

When sending excel file to mail recipient as an attachment, the in
When sending an excel file to a Mail recipient as an attachment, the internet connection wizard comes up wanting to set up email account. The user has Outlook already set up for her. What causes this and how can I make it send through her outlook mail? Thanks Hi Check out if Outlook is your mail program for Office Start>Settings>Control Panel....Internet options (Program Tab) Close Excel first before you make a change. -- Regards Ron de Bruin http://www.rondebruin.nl "ibeaprogrammer" <ibeaprogrammer@discussions.microsoft.com> wrote in message news:8DC503CA-7...

WriteFile and ERROR_INSUFFICIENT_BUFFER
I'm using the WriteFileEx function to write a file asynchronously. However I sometimes get the error code ERROR_INSUFFICIENT_BUFFER (with GetLastError), although the function still returns a success and the data gets written ok. However I don't think it is actually doing an asynchronous write. I open the file with a call to CreateFile, with the flags: FILE_ATTRIBUTE_NORMAL | FILE_FLAG_OVERLAPPED | FILE_FLAG_NO_BUFFERING To satisfy the No buffering, I use VirtualAlloc and make sure source/dest and size values are all aligned to sector sizes. That bit seems fine. Also, if I try...

Converting a formula to data
I hope I can explain this well enough to be understood. I have a LONG column. Each cell in this column contains a formula (=(M331/1000000)+37) which returns a value to the cell. However, when you click on a completed cell, you get the formula in the formula bar. What I would like to do; after I have completed all my data input; is to highlight the cells in this column, and replace the formula with the value in each cell, so that if I want to use this value somewhere else, I copy the value, not the formula. Thanks. -- Howard Hi Howard Just highlight the cells in that ...

Seondary axes line-chart not showing as per data
I have a plotted a periodic 100% stacked column chart with 6 data rows (meaning 6 components of data for each period). I have a secondary periodic data with 5 compenents that I have plotted on secondary axis. Both the data are in per cents. I have equalized the scale on both axes. The problem is that the lines plotted on secondary axes are not plotted in accordance with the values. For example, one data row with values 2% to 6% is appearing near 100% line (100% on both axes are aligned across the same line). Even strange is that when I change the "Series Order" of the same lim...

printing reply with "From: Setn: To: Subject: lines before sending
I send my reply to Print and the only thing that prints is my actual reply. I want it to print the From: Sent: To: Subject: etc. - Now, after I send a reply, I go into my Sent items and then print my reply in order to get the headings to show. What can I do? ...

Importing data to Excel using a keyboard shortcut
I am trying to bring data into Excel from a web based report. I can easily do this at home by right clicking on the web based data and then "export to Excel". However, at work, the right click mouse function is disabled due to security reasons. Are there any keyboard shortcuts that essentially duplicate the right click, export to Excel function? There are none indicated on the (right click) drop down window when viewed from home. Thanks for your help -- Ken McI Possible idea: On a mjority of newer keyboards, there is a button between the right Alt and Ctrl b...

Sending email with Outlook
I could not send email with Outlook or Outlook Express through my Comcast high speed account, I could receive email though. Finally after 6 Comcast techs on the phone a friend of mine said to change the SMTP setting from 25 to 465 and that fixed the problem. At least in Outlook Express. I then put in the same settings into Outlook and it still will not send mail, only receive. Any ideas? I'm using Windows XP. This is a laptop and I took it to work and hooked it to Comcast and it sends and receives email just fine set to SMTP port 25. Since the results you experienced contradict eachothe...

Can't send mail through public wireless network
That sums it up. Receiving mail is not a problem, but almost every attempt to send through Outlook while on a public wireless network fails, with the message from System Administrator stating "Undeliverable: e-mail", with no further details. I suspect that the ISP running the wireless network is not relaying any mail, but the message says nothing about blocking relay. Is this the case, or is there something else I'm missing? I can send mail fine by logging on to my webmail. Thanks, Alex ...