2013-03-07 195 views
4

我为项目使用Zebra KR403收据打印机,并且需要以编程方式从打印机读取状态(缺纸,近端纸张,打印头打开,卡纸等)。在ZPL文档中,我发现我需要发送一个~HQES命令,并且打印机回应其状态信息。如何从Zebra收据打印机读回状态?

在这个项目中,打印机通过USB连接,但我想它可能更容易让它通过COM端口连接它,并从那里工作,让它通过USB工作。我可以打开与打印机的通信,并向它发送命令(我可以打印测试收据),但每当我尝试读取任何内容时,它都会永久挂起,永远不会读取任何内容。

下面是我使用的代码:

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; 
} 

我发现,当我打印测试接收(先打电话SendToPrinter())没有获取打印,直到我关闭手柄stream.Close()。调用stream.Write()

  • 调用stream.Flush(),但仍没有得到读取(没有东西无论是打印,直到我叫stream.Close()
  • 只发送命令,然后关闭数据流:我做了这些测试,但无济于事,立即重新开放,并尝试读取
  • 开放两个手柄,手柄上的1,靠近手柄1读写,处理2.什么

有没有人有任何运气从斑马打印机回读状态?或者任何人有任何想法,我可能做错了什么?

+0

我想你会获得更多的牵引力(更好的控制)[的SerialPort(HTTP ://msdn.microsoft.com/en-us/library/system.io.ports.serialport.aspx)类比一般的FileStream为此。 – 2013-03-07 18:46:20

+0

@ 500-InternalServerError现在我通过COM端口连接它,因为我认为这会比USB更容易,但在实际项目中,打印机通过USB连接,因此SerialPort类不是此处的选项。 – MarioVW 2013-03-07 19:22:58

+0

为什么不呢?顾名思义,USB端口也是串行端口。 – 2013-03-07 19:25:54

回答