【问题标题】:Handling events from Word using dynamic com interop from C#使用 C# 中的动态 com 互操作处理来自 Word 的事件
【发布时间】:2010-08-18 14:36:18
【问题描述】:

从 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 的委托分配给动态对象 word.Quit。那么如何捕捉这个事件呢?

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

【问题讨论】:

    标签: c# com delegates silverlight-4.0 event-handling


    【解决方案1】:

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

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

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

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

    HTH。

    【讨论】:

    • 确实是这样。
    【解决方案2】:

    我还没有尝试过,但它可能会起作用:

    word.Quit += new WordQuitEventHandler(WordOnQuit);
    

    基本上,编译器目前不知道您要将方法组转换为什么类型 - 上面的代码应该提供足够的信息。

    【讨论】:

    • 我试过了,它说它不知道如何处理委托:“Unhandled object type [Test+WordQuitEventHandler] in ConvertObjectToInteropValue”
    • 我找到了一个例子,但我不能真正尝试它,直到我再次工作:msdn.microsoft.com/en-us/library/…
    猜你喜欢
    • 2011-08-25
    • 2011-08-05
    • 2011-05-12
    • 2012-03-03
    • 2020-11-10
    • 1970-01-01
    • 2013-02-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多