词.互操作文档已关闭
本文关键字:文档 互操作 | 更新日期: 2023-09-27 17:53:51
我正在尝试将单词拼写检查集成到WinForms应用程序中。到目前为止,互操作库一直是一个令人头疼的问题。折腾了好几个小时后,我终于让拼写检查工作起来了。CheckSpellingOnce以及底层CheckSpelling方法按预期执行,但是只要我调用getspellingsuggestion,应用程序就会抛出…
抛出异常:'System.Runtime.InteropServices. '附加信息:该命令不存在
第一个想法是底层COM对象从其各自的包装器断开连接,因为_wordApp是从创建它的不同线程调用的。因此,我尝试从CheckSpelling()中调用它,不幸的是结果相同。我还尝试打开和关闭文档,向现有应用程序实例添加新文档,以及从_document对象本身(_document. application . getspellingsuggestions)获取应用程序。
那是怎么回事呢?
额外的信息:CheckSpellingOnce方法从UI调用时,计时器事件被触发(一旦用户停止在RichTextField输入)-所以多次-使用相同的_wordApp对象,因为我试图避免启动多个实例的winword.exe。
/// <summary>
/// Checks spelling with the text from the provided richtextbox in a new thread.
/// </summary>
public void CheckSpellingOnce()
{
_checkerThread = new Thread(new ThreadStart(CheckSpelling));
_checkerThread.Start();
}
/// <summary>
/// Checks the spelling of a richtextbox. Raises an event with the result when done.
/// </summary>
private void CheckSpelling()
{
if (_shouldBeChecking)
{
RaiseStatusChanged(SpellCheckStatus.Working);
Word.ProofreadingErrors toReturn = null;
UpdateStringFromTextBox();
if (!string.IsNullOrEmpty(_fromTextBox))
{
_document.Content.Delete();
_document.Words.First.InsertBefore(_fromTextBox);
_document.Content.LanguageID = _language; //Must be set specifically here for some f***d reason.
toReturn = _document.SpellingErrors;
RaiseSpellingChecked(toReturn);
RaiseStatusChanged(SpellCheckStatus.Idle);
}
}
}
public Word.SpellingSuggestions GetSpellingSuggestions(string word)
{
//throw new NotImplementedException();
Word.SpellingSuggestions toReturn = _wordApp.GetSpellingSuggestions(word, _missing, _missing, _missing, _missing, _missing, _missing);
return toReturn;
}
即使使用了GetSpellingSuggestions的实现,它也会在"toReturn"行发出报错,而不是在它上面的行…
public void GetSpellingSuggestions(string word)
{
//throw new NotImplementedException();
var _suggestionThread = new Thread(new ThreadStart(() =>
{
_document.Content.Delete();
_document.Words.First.InsertBefore(word);
_document.Content.LanguageID = _language;
Word.SpellingSuggestions toReturn = _wordApp.GetSpellingSuggestions(word, _missing, _missing, _missing, _missing, _missing, _missing);
Debug.Print(toReturn[0].ToString());
}));
_suggestionThread.Start();
}
/// <summary>
/// Opens a Word interop lib document.
/// </summary>
/// <returns></returns>
private Word._Document OpenDocument()
{
object visible = false;
_document = _wordApp.Documents.Add(_missing, _missing, _missing, visible);
return _document;
}
这是我打开文档的方式(内存中)
将visible参数设置为"true"解决了这个问题——但由于某种原因(就像我的情况一样),应用程序进程仍然在后台运行。我的理论是,winword.exe保持不可见,直到像Document.CheckSpelling()这样的方法被调用-这实际上调用了Word GUI。
如果有人需要,可以提供更多的代码。
谢谢你的建议,干杯!