使用此知识库文章作为示例:http://support.microsoft.com/kb/322091/en-us,
我正在尝试将原始数据(字节数组)发送到热敏打印机。为此,我使用上面文章中的以下方法:
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;
}
所以我发送一个数组:
bool bSuccess = false;
...
try
{
bSuccess = RawPrinterHelper.SendBytesToPrinter(printerName, pUnmanagedBytes, nLength);
}
catch (Exception ex)
{
failprint = ex.Message;
}
if (bSuccess == true)
{
MessageBox.Show("Text printed");
}
else
{
MessageBox.Show("Printing failed: " + failprint);
}
如果打印机可用,一切正常,我将MessageBox.Show("Text printed");
与实际打印结合在一起。但是,如果我关闭打印机(在尝试打印之前),我不会打印失败 MessageBox。相反,应用程序被冻结并等待打印机打开,然后排队的打印作业成功打印,应用程序解冻,我得到MessageBox.Show("Text printed")
。
我在尝试捕获失败的打印作业时错误,而应用程序没有处于冻结等待状态?
答案 0 :(得分:1)
你应该异步运行WritePrinter方法然后检查Marshal.GetLastWin32Error();
答案 1 :(得分:0)
这是老派。您可能想要使用此
// Create the printer server and print queue objects
LocalPrintServer localPrintServer = new LocalPrintServer();
PrintQueue defaultPrintQueue = LocalPrintServer.GetDefaultPrintQueue();
// Call AddJob
PrintSystemJobInfo myPrintJob = defaultPrintQueue.AddJob();
// Write a Byte buffer to the JobStream and close the stream
Stream myStream = myPrintJob.JobStream;
Byte[] myByteBuffer = UnicodeEncoding.Unicode.GetBytes("This is a test string for the print job stream.");
myStream.Write(myByteBuffer, 0, myByteBuffer.Length);
myStream.Close();
source msdn