【问题标题】:Document printed via Word Interop immediately disappears from print queue通过 Word Interop 打印的文档会立即从打印队列中消失
【发布时间】:2017-04-03 09:37:03
【问题描述】:

我有一个 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 事件,但我不能立即使用看看这在使用互操作时是否适用。这会是一种无需轮询即可实现我想要的方法吗?

【问题讨论】:

  • 您可以轮询 wordApp.BackgroundPrintingStatus 的计数并等待它为 0。我无法对此进行测试以验证,所以只能发表评论。
  • @Equalsk 我最终使用了您建议的方法(尽管我不喜欢轮询...我想我可以在单独的线程上进行)。无论如何,如果你想做出相同效果的答案,我会接受。

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


【解决方案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); } });

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-04-09
    • 1970-01-01
    • 2023-03-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多