开发者

Word - Reflecting Events

I am trying to use reflection to get all the events in word and then create a delegate that I can add to one of these events. The code I have so far is: Thanks for the response.

Well the idea is to pass the name of an event such as DocumentBeforeSave to a method a bit like:

EventInfo p = getEvent(this.Application, "DocumentBeforeSave");

public EventInfo getEvent(Word.Application wordApp, string eventName)
    {
      Type wordType = wordApp.GetType();

      EventInfo[] f = wordApp.GetType().GetEvents();
      EventInfo result = (from o in f
                where o.Name == eventName
                select o).FirstOrDefault();
      return result;
    }

Now this gives me an EventInfo of Microsoft.Office.Interop.Word.ApplicationEvents4_DocumentBeforeSaveEventHandler. Which to me looks like Word.ApplicationEvents4_DocumentBeforePrintEventHandler which can assign and eventhandler with +=;

I see that the EventInfo has an AddEventHandler method. I am hoping that I can attach my own delegate to handle when the DocumentBeforeSave event fires.

The problem is, I just don't seem to be able to get the delegate right. I have been playing around with this:

    MethodInfo[] myArrayMethodInfo = msw.GetMethods(BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly);
          MethodInfo r = (from o in myArrayMethodInfo
                  where o.Name == "add_" + p.Name
                  select o).FirstOrDefault();

Delegate del = Delegate.CreateDelegate(p.EventHandlerType,r, false);

But the Delegate is al开发者_如何学Goways null. Is this just not possible or am I just doing it wrong.

Thanks


You can create an Expression Tree.

This feature allows you to compile code at runtime into an arbitrary delegate type.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜