【发布时间】: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