通过Word Interop打印的文档立即从打印队列中消失

时间:2017-04-03 09:37:04

标签: c# winforms printing ms-word office-interop

我有一个C#WinForm应用程序,通过在书签上放置文本打开并填写MS Word dotx模板,然后尝试打印它,全部使用MS Word Interop 15。

一切似乎都很顺利,打印对话框显示并完成正常,打印作业显示在打印队列中(即MS Windows 10上“设备和打印机”中的“查看打印内容”窗口)。但是,在可以假脱机之前,作业会立即从队列中消失! (文件在“假脱机”状态下显得非常简短,并且不打印 - 打印机永远不会得到这份工作)

这是我的代码(为简洁起见,删除了异常检查):

using Word = Microsoft.Office.Interop.Word;
private void Print_Click(object sender, EventArgs e)
{
    // Open the MS Word application via Office Interop
    Word.Application wordApp = new Word.Application();
    Word.Document wordDoc;
    // Open the template
    wordDoc = wordApp.Documents.Add(Template: ContractTemplatePath, Visible: false);
    // Ensure the opened document is the currently active one
    wordDoc.Activate();

    // Set the text for each bookmark from the corresponding data in the GUI
    SetBookmarkText(wordDoc, "Foo", fooTextBox.Text);
    // ... There's a whole bunch of these ... then:

    // Instantiate and configure the PrintDialog
    var pd = new PrintDialog()
    {
        UseEXDialog = true,
        AllowSomePages = false,
        AllowSelection = false,
        AllowCurrentPage = false,
        AllowPrintToFile = false
    };

    // Check the response from the PrintDialog
    if (pd.ShowDialog(this) == DialogResult.OK)
    {
        // Print the document
        wordApp.ActivePrinter = pd.PrinterSettings.PrinterName;
        wordDoc.PrintOut(Copies: pd.PrinterSettings.Copies);
    }

    // Close the document without saving the changes (once the 
    // document is printed we don't need it anymore). Then close 
    // the MS Word application.
    wordDoc.Close(SaveChanges: false);
    wordApp.Quit(SaveChanges: false);
}

我在这里唯一可以想到的可能是因为我在将文件发送到打印机后立即取消了该文档,然后该作业尚未完全发送,因此它会自行删除或其他内容。如果 这个案例,那么我如何确定需要多长时间保留文档以及等待它的最佳方式是什么?

编辑:我做过另一小部分研究(暂时还没有时间对此进行更多研究)这表明我可以使用PrintEnd事件,但我无法立即看看这在使用Interop时是否适用。如果没有民意调查,这会是一种实现我想要的方法吗?

1 个答案:

答案 0 :(得分:1)

一种解决方案是轮询Word应用程序的BackgroundPrintingStatus属性。它包含仍在打印队列中等待的文档的计数。当此计数大于0时,仍有等待打印的文档。

有很多方法可以实现这一目标。这是一个阻止UI的简单循环:

// Send document to printing queue here...

while (wordApp.BackgroundPrintingStatus > 0)
{
    // Thread.Sleep(500);
}

// Printing finished, continue with logic

或者,您可能希望将其包装在任务中,以便在等待时可以执行其他操作:

await Task.Run(async () => { while (wordApp.BackgroundPrintingStatus > 0) 
                                   { await Task.Delay(500); } });
相关问题