[英]Error occur during using backgroundworker in ms document C#
我試圖使用進度條來顯示MS Word文檔中的循環操作進度,因此我使用了后台工作程序在循環操作期間更新進度條,如以下代碼所示。
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Word = Microsoft.Office.Interop.Word;
using Microsoft.Office.Tools.Word;
namespace prog
{
public partial class PGB : Form
{
public PGB()
{
InitializeComponent();
}
private static int Mx;
private void PGB_Load(object sender, EventArgs e)
{
Mx = 100;
PG.Maximum = Mx;
PG.Step = 1;
PG.Value = 0;
BGW.RunWorkerAsync();
}
private void BGW_DoWork(object sender, DoWorkEventArgs e)
{
for (int j = 0; j <= Mx-1; j++)
{
Loop_Opt(j+1);
BGW.ReportProgress((j));
}
}
private void BGW_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
PG.Value = e.ProgressPercentage;
}
private void BGW_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
MessageBox.Show("Done");
}
public static void Loop_Opt(int n)
{
Word.Application wordApp;
Word.Document oDoc = null;
wordApp = (Word.Application)System.Runtime.InteropServices.Marshal.GetActiveObject("Word.Application");
oDoc = wordApp.ActiveDocument;
Document DD = Globals.Factory.GetVstoObject(oDoc);
for (int i = 1; i <= oDoc.Bookmarks.Count; i++)
{//loop operation//}
}
}
}
發生錯誤的行是Loop_Opt()類的以下行:
Document DD = Globals.Factory.GetVstoObject(oDoc);
錯誤消息如下:
[Unable to cast COM object of type 'System.__ComObject' to interface type 'Microsoft.VisualStudio.Tools.Office.Runtime.Interop.IHostItemFactoryNoMAF'. This operation failed because the QueryInterface call on the COM component for the interface with IID '{A0885C0A-33F2-4890-8F29-25C8DE7808F1}' failed due to the following error: No such interface supported (Exception from HRESULT: 0x80004002 (E_NOINTERFACE)).]
提前致謝
經過長時間的研究和試驗,我認為使用Background worker控件沒有一個簡單的解決方案。
因此,我使用普通的方式來更新進度條,而不是如下面的代碼中所示的Background worker控件,它可以正常工作,但效率與后台worker控件相同。
public void Loop_Opt()
{
Word.Application wordApp;
Word.Document oDoc = null;
wordApp = (Word.Application)System.Runtime.InteropServices.Marshal.GetActiveObject("Word.Application");
oDoc = wordApp.ActiveDocument;
Document DD = Globals.Factory.GetVstoObject(oDoc);
PG.Maximum = oDoc.Bookmarks.Count;
PG.Step = 1;
PG.Value = 1;
for (int i = 1; i <= oDoc.Bookmarks.Count; i++)
{
//loop operation//
PG.PerformStep();
Thread.Sleep(100);
Application.DoEvents();
}
}
Office應用程序使用單線程單元模型(STA)。 您不應該在輔助線程上使用它們。 此外,Globals.Factory.GetVstoObject方法只能在基於VSTO的加載項中使用。
如果僅處理開放XML文檔,我建議使用Open XML SDK 。 或使用任何其他第三方組件。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.