使用ReadPrinter Winspool.Drv读取打印机数据



我有通过USB连接的Zebra打印机,我正在尝试使用命令^XA^HWR:^XZ读取打印机的内存。该命令适用于TCP/IP。

我甚至不确定我的方法头是否正确。

[DllImport("winspool.Drv", EntryPoint = "ReadPrinter", SetLastError = true, ExactSpelling = true, CallingConvention = CallingConvention.StdCall)]
static extern bool ReadPrinter(IntPtr hPrinter, IntPtr pBuf, int cbBuf, out int pNoBytesRead);

方法ReadPrinter总是返回false和0个读取字节。当我尝试获取LastWin32Error时,我会得到各种0、6或63(ERROR_SUCCESS-尽管它返回false且没有数据,ERROR_INVALID_HANDLEERROR_PRINT_CANCELLED(,这取决于我正在尝试的情况。我尝试了几种方法头和不同的方法,但都没有成功读取数据。我启用了"双向支持"并安装了打印机驱动程序。它可能看起来像是其他线程的副本,但我已经完成了它们,它们都没有帮助。

代码片段:

private static void SendBytesToPrinter(string printerName, IntPtr pointerBytes, int bytesCount)
{
int written = 0;
PrintResult printResult = new PrintResult();
IntPtr pointerPrinter = new IntPtr(0);
DOCINFOA docInfo = new DOCINFOA();
bool success = false;
docInfo.DocName = "RAW Document";
docInfo.DataType = "RAW";
try
{
if (OpenPrinter(printerName.Normalize(), out pointerPrinter, IntPtr.Zero))
{
if (StartDocPrinter(pointerPrinter, 1, docInfo))
{
if (StartPagePrinter(pointerPrinter))
{
success = WritePrinter(pointerPrinter, pointerBytes, bytesCount, out written);
EndPagePrinter(pointerPrinter);
}
EndDocPrinter(pointerPrinter);
}
// READ HERE
Int32 bufLen = 32;
IntPtr pStatus = Marshal.AllocCoTaskMem(bufLen);
Int32 statusLen = 0;
bool bSuccess = ReadPrinter(hPrintJob, pStatus, bufLen, out statusLen);
ClosePrinter(pointerPrinter);
} 
} catch (Exception ex) { }
}

我使用Visual Basic示例,使用FileStreamsStreamReaders解决了这个问题。感谢@kunif指出示例代码。

kernel32.dll取代winspool.Drv

[DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Auto)]
private static extern SafeFileHandle CreateFile(string lpFileName, EFileAccess dwDesiredAccess, 
EFileShare dwShareMode, IntPtr lpSecurityAttributes, 
ECreationDisposition dwCreationDisposition, 
EFileAttributes dwFlagsAndAttributes, 
IntPtr hTemplateFile);
private static string ReadUsbPort(StreamReader sr)
{
string readResult = string.Empty;
if (sr != null && sr.BaseStream != null)
{
do
{
readResult += sr.ReadLine();
readResult += "r";
}
while (sr.EndOfStream == false);
}
return readResult;
}

非常有用的是GUID_DEVINTERFACE_USB_DEVICE和WinUSBNet

相关内容

  • 没有找到相关文章

最新更新