gpt4 book ai didi

c# - 使用来自 C# 的动态 com interop 处理来自 Word 的事件

转载 作者:行者123 更新时间:2023-11-30 21:20:00 25 4
gpt4 key购买 nike

从 Silverlight 4 开始,启动 Word 并让用户执行某些操作非常容易:

dynamic word = System.Runtime.InteropServices.Automation.CreateObject("Word.Application");
word.Visible = true;
word.Documents.Open("test.doc");

MS Word 公开了一个 Quit 事件 [1]。我想处理这个事件,但对于我的生活我无法弄清楚如何。我试着这样做:

public delegate void WordQuitEventHandler(object sender, ref bool cancel);
public event WordQuitEventHandler OnQuit;
private void WordOnQuit(dynamic sender, ref bool cancel)
{
if (OnQuit != null)
{
OnQuit(this, ref cancel);
}
}

然后做

word.Quit = WordOnQuit;

word.Quit += WordOnQuit;

但是不可能将 WordOnQuit 的委托(delegate)分配给动态对象 word.Quit。那么如何捕捉这个事件呢?

[1] http://msdn.microsoft.com/en-us/library/aa211898(v=office.11).aspx

最佳答案

为了完整起见,您正在寻找的是...

AutomationEvent quitEvent = AutomationFactory.GetEvent(word,"Quit");
quitEvent.EventRaised += new EventHandler<AutomationEventArgs>(quitEvent_EventRaised);

当然,您可以根据需要内联回调。

另外,我发现这个事件可能有点古怪。大多数时候它会触发...大部分时间 :-)

HTH.

关于c# - 使用来自 C# 的动态 com interop 处理来自 Word 的事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3513208/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com