I am using the Zebra KR403 receipt printer for the project, and I need to programmatically read the status from the printer (from paper, paper near the print head, paper jams, etc.). In the ZPL documentation, I found that I need to send the ~HQES , and the printer responds with its status information.
In the project, the printer is connected via USB, but I realized that it might be easier to make it work by connecting it via the COM port and work from there to make it work through USB. I can open a connection with the printer and send him commands (I can print test receipts), but whenever I try to read something back, it just hangs forever and never reads anything.
Here is the code I'm using:
public Form1() { InitializeComponent(); SendToPrinter("COM1:", "^XA^FO50,10^A0N50,50^FDKR403 PRINT TEST^FS^XZ", false); // this prints OK SendToPrinter("COM1:", "~HQES", true); // read is never completed } [DllImport("kernel32.dll", SetLastError = true)] static extern SafeFileHandle CreateFile( string lpFileName, FileAccess dwDesiredAccess, uint dwShareMode, IntPtr lpSecurityAttributes, FileMode dwCreationDisposition, uint dwFlagsAndAttributes, IntPtr hTemplateFile); private int SendToPrinter(string port, string command, bool readFromPrinter) { int read = -2; // Create a buffer with the command Byte[] buffer = new byte[command.Length]; buffer = System.Text.Encoding.ASCII.GetBytes(command); // Use the CreateFile external func to connect to the printer port using (SafeFileHandle printer = CreateFile(port, FileAccess.ReadWrite, 0, IntPtr.Zero, FileMode.Open, 0, IntPtr.Zero)) { if (!printer.IsInvalid) { using (FileStream stream = new FileStream(printer, FileAccess.ReadWrite)) { stream.Write(buffer, 0, buffer.Length); // tries to read only one byte (for testing purposes; in reality many bytes will be read with the complete message) if (readFromPrinter) { read = stream.ReadByte(); // THE PROGRAM ALWAYS HANGS HERE!!!!!! } stream.Close(); } } } return read; }
I found out that when I print a test receipt (the first call to SendToPrinter() ), nothing is printed until I close the handle with stream.Close() . I did these tests, but to no avail:
- calling
stream.Flush() after calling stream.Write() but still nothing is read (and nothing prints until I call stream.Close() ) - just send a command and then close the stream, reopen immediately and try to read
- open two handles, write on handle 1, close handle 1, read handle 2. nothing
Is anyone really lucky with the return status from the Zebra printer? Or does anyone know what I can do wrong?