I'm using a Zebra KR403 receipt printer for a project and I need to programatically read the status from the printer (out of paper, paper near-end, printhead open, paper jam, etc). In the ZPL documentation I found that I need to send a ~HQES
command and the printer responds with its status information.
In the project the printer is connected via USB, but I figured it may be easier to get it to work connecting it via COM port and work from there to get it to work over USB. I am able to open communication with the printer and send commands to it (I can print test receipts), but whenever I try to read anything back it simply hangs forever and never gets to read anything.
Here's 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've found out that when I print the test receipt (first call to SendToPrinter()
) nothing gets printed until I close the handle with stream.Close()
. I've made these tests but to no avail:
stream.Flush()
after calling stream.Write()
, but still nothing gets read (and nothing gets printed either until I call stream.Close()
)Has anyone has had any luck reading back status from a Zebra printer? Or anyone has any idea of what I may be doing wrong?
As pointed out by @l33tmike in the comments, the answer to this question has already been posted on another question: Which SDK should I use for KR403 Zebra Printer