2

我正在使用LibUsbDotNet与我的 GC420t Zebra 打印机进行通信。

在打印方面效果很好:

MyUsbDevice = UsbDevice.OpenUsbDevice(MyUsbFinder);
if (MyUsbDevice == null) throw new Exception("Device Not Found.");

IUsbDevice wholeUsbDevice = MyUsbDevice as IUsbDevice;
if (!ReferenceEquals(wholeUsbDevice, null))
{
    wholeUsbDevice.SetConfiguration(1);
    wholeUsbDevice.ClaimInterface(0);
}

UsbEndpointWriter writer = MyUsbDevice.OpenEndpointWriter(WriteEndpointID.Ep01);

int bytesWritten;
if (writer.Write(Encoding.Default.GetBytes(someString), 2000, out bytesWritten) != ErrorCode.None)
    throw new Exception(UsbDevice.LastErrorString);

但我找不到让我的阅读器代码工作的方法......总是返回读取的 0 个字节。我把它放在上面代码的末尾,打开了我的打印机盖(这肯定会给我一些错误代码)。

UsbEndpointReader reader = MyUsbDevice.OpenEndpointReader(ReadEndpointID.Ep01);

// above code...

ErrorCode ec = ErrorCode.None;
byte[] readBuffer = new byte[1024];
while (ec == ErrorCode.None)
{
    int bytesRead;
    ec = reader.Read(readBuffer, 5000, out bytesRead);
    Console.WriteLine("{0} bytes read", bytesRead);
    Console.Write(Encoding.Default.GetString(readBuffer, 0, bytesRead));
}

如果您知道如何使这项工作......或者如果您知道更好/更快/更简单的方法来做到这一点,我会接受的,谢谢。

编辑:所以我尝试了更多的东西,做了更多的研究。

使用 winspool 访问打印机状态 -> Returned 0 即使我从打印机中取出了介质,整洁。好吧,我猜它只是初始化为 0,并且没有收到任何值。此代码正在使用该OpenPrinter/GetPrinter/ClosePrinter模式。

LibUsbDotNet -> 尝试了所有列出的读取状态的方法,总是读取 0 个字节。

RawPrinterHelper -> 适用于打印,但没有找到获取打印机状态的方法。

然后我读到一些东西(不记得在哪个网站上)说你必须在打印机打印时阅读状态。怎么可能呢?

编辑:为了完整起见,这是我为打印机生成命令的方式(这可能无济于事,因为它在打印时再次完美地工作):

StringBuilder sb = new StringBuilder().AppendLine()
    .AppendLine("N")
    .AppendLine("^ee") // The "give me an answer" code, also tested at the end of the commands, or as the only command (with newline and N)
    // more appending...
    .AppendLine(String.Format("P{0},{1}", 1, 1));

编辑:仅作记录,我很确定您可以获得此 GC420t 状态的原因......是因为您可以使用 Zebra Setup Utilities。如果您使用提供的工具(Open Communication With Printer )发送^ee,您将正确获得错误代码。我只需要知道它是如何做到的。

4

2 回答 2

0

去年使用 KR403 编写了一个 kiosk 应用程序。我能够使用下面的博客文章通过 USB 成功打印并轮询打印机的状态,以查看是否有卡纸不足等。

http://danielezanoli.blogspot.com/2010/06/usb-communications-with-zebra-printers.html

var printerStatusCommand = Encoding.GetEncoding(850).GetBytes(@"~HQES");
try
{
    var zebraConnection = new ZebraUsbStream();

    zebraConnection.Write(printerStatusCommand, 0, printerStatusCommand.Length);

    var statusReturn = new byte[800];
    var bytesRead = zebraConnection.Read(statusReturn, 0, 800);

    if (bytesRead >= 132)
    {
        var stringResult = Encoding.Default.GetString(statusReturn.ToArray());
        Console.WriteLine(stringResult);
    }
}
catch
{
    Console.WriteLine("Error");
}

stringResult 有很多额外的字符串/字节解析,因为状态值存储为返回字节内的单个位,但打印机文档很好地涵盖了格式。

于 2015-02-22T22:05:49.340 回答
0

尝试使用上面的类:

   public class cPrintHelper
{
    // Structure and API declarions:
    [StructLayout(LayoutKind.Sequential, CharSet=CharSet.Ansi)]
    public class DOCINFOA
    {
        [MarshalAs(UnmanagedType.LPStr)] public string pDocName;
        [MarshalAs(UnmanagedType.LPStr)] public string pOutputFile;
        [MarshalAs(UnmanagedType.LPStr)] public string pDataType;
    }
    [DllImport("winspool.Drv", EntryPoint="OpenPrinterA", SetLastError=true, CharSet=CharSet.Ansi, ExactSpelling=true, CallingConvention=CallingConvention.StdCall)]
    public static extern bool OpenPrinter([MarshalAs(UnmanagedType.LPStr)] string szPrinter, out IntPtr hPrinter, IntPtr pd);

    [DllImport("winspool.Drv", EntryPoint="ClosePrinter", SetLastError=true, ExactSpelling=true, CallingConvention=CallingConvention.StdCall)]
    public static extern bool ClosePrinter(IntPtr hPrinter);

    [DllImport("winspool.Drv", EntryPoint="StartDocPrinterA", SetLastError=true, CharSet=CharSet.Ansi, ExactSpelling=true, CallingConvention=CallingConvention.StdCall)]
    public static extern bool StartDocPrinter( IntPtr hPrinter, Int32 level,  [In, MarshalAs(UnmanagedType.LPStruct)] DOCINFOA di);

    [DllImport("winspool.Drv", EntryPoint="EndDocPrinter", SetLastError=true, ExactSpelling=true, CallingConvention=CallingConvention.StdCall)]
    public static extern bool EndDocPrinter(IntPtr hPrinter);

    [DllImport("winspool.Drv", EntryPoint="StartPagePrinter", SetLastError=true, ExactSpelling=true, CallingConvention=CallingConvention.StdCall)]
    public static extern bool StartPagePrinter(IntPtr hPrinter);

    [DllImport("winspool.Drv", EntryPoint="EndPagePrinter", SetLastError=true, ExactSpelling=true, CallingConvention=CallingConvention.StdCall)]
    public static extern bool EndPagePrinter(IntPtr hPrinter);

    [DllImport("winspool.Drv", EntryPoint="WritePrinter", SetLastError=true, ExactSpelling=true, CallingConvention=CallingConvention.StdCall)]
    public static extern bool WritePrinter(IntPtr hPrinter, IntPtr pBytes, Int32 dwCount, out Int32 dwWritten );

    // SendBytesToPrinter()
    // When the function is given a printer name and an unmanaged array
    // of bytes, the function sends those bytes to the print queue.
    // Returns true on success, false on failure.
    public static bool SendBytesToPrinter( string szPrinterName, IntPtr pBytes, Int32 dwCount)
    {
        Int32    dwError = 0, dwWritten = 0;
        IntPtr    hPrinter = new IntPtr(0);
        DOCINFOA    di = new DOCINFOA();
        bool    bSuccess = false; // Assume failure unless you specifically succeed.

        di.pDocName = "My C#.NET RAW Document";
        di.pDataType = "RAW";

        // Open the printer.
        if( OpenPrinter( szPrinterName.Normalize(), out hPrinter, IntPtr.Zero ) )
        {
            // Start a document.
            if( StartDocPrinter(hPrinter, 1, di) )
            {
                // Start a page.
                if( StartPagePrinter(hPrinter) )
                {
                    // Write your bytes.
                    bSuccess = WritePrinter(hPrinter, pBytes, dwCount, out dwWritten);
                    EndPagePrinter(hPrinter);
                }
                EndDocPrinter(hPrinter);
            }
            ClosePrinter(hPrinter);
        }
        // If you did not succeed, GetLastError may give more information
        // about why not.
        if( bSuccess == false )
        {
                dwError = Marshal.GetLastWin32Error();
        }
        return bSuccess;
    }

    public static bool SendFileToPrinter( string szPrinterName, string szFileName )
    {
        // Open the file.
        FileStream fs = new FileStream(szFileName, FileMode.Open);
        // Create a BinaryReader on the file.
        BinaryReader br = new BinaryReader(fs);
        // Dim an array of bytes big enough to hold the file's contents.
        Byte []bytes = new Byte[fs.Length];
        bool bSuccess = false;
        // Your unmanaged pointer.
        IntPtr pUnmanagedBytes = new IntPtr(0);
        int nLength;

        nLength = Convert.ToInt32(fs.Length);
        // Read the contents of the file into the array.
        bytes = br.ReadBytes( nLength );
        // Allocate some unmanaged memory for those bytes.
        pUnmanagedBytes = Marshal.AllocCoTaskMem(nLength);
        // Copy the managed byte array into the unmanaged array.
        Marshal.Copy(bytes, 0, pUnmanagedBytes, nLength);
        // Send the unmanaged bytes to the printer.
        bSuccess = SendBytesToPrinter(szPrinterName, pUnmanagedBytes, nLength);
        // Free the unmanaged memory that you allocated earlier.
        Marshal.FreeCoTaskMem(pUnmanagedBytes);
        return bSuccess;
    }
    public static bool SendStringToPrinter( string szPrinterName, string szString )
    {
        IntPtr pBytes;
        Int32 dwCount;
        // How many characters are in the string?
        dwCount = szString.Length;
        // Assume that the printer is expecting ANSI text, and then convert
        // the string to ANSI text.
        pBytes = Marshal.StringToCoTaskMemAnsi(szString);
        // Send the converted ANSI string to the printer.
        SendBytesToPrinter(szPrinterName, pBytes, dwCount);
        Marshal.FreeCoTaskMem(pBytes);
        return true;
    }
}

和电话:

cPrintHelper.SendStringToPrinter(printerName, fileIn);

fileIn 是转义序列代码。

fileIn 应该是这样的。N I8,D Q120,24 q245 S4 D12 ZB A100,10,0,3,2,2,N,"A" A140,10,0,3,2,2,N,"B" P1

1

此代码在斑马标签打印机 2844 上成功运行 5 年。

希望有帮助。:)

于 2014-05-26T11:50:36.067 回答