繁体   English   中英

WPF 应用程序将原始数据发送到打印机异常处理

[英]WPF app sending raw data to a printer exception-handling

以此知识库文章为例: 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.Show("Text printed")

在没有应用程序冻结、等待 state 的情况下,我试图捕捉失败的打印作业在哪里错了?

您应该异步运行 WritePrinter 方法,然后检查 Marshal.GetLastWin32Error();

这是老学校。 你可能想用这个

// 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();

来源 msdn

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM