开发者

Adding a delegate to an eventhandler

开发者 https://www.devze.com 2023-02-08 20:00 出处:网络
I am trying to add a delegate to an EventHandler in word but keep getting an Argument Exception while using the below code:

I am trying to add a delegate to an EventHandler in word but keep getting an Argument Exception while using the below code:

Type ty = this.Aplication.GetType().GetEvent("DocumentBeforeClose").EventHandlerType;
this.Application.GetType().GetEvent("DocumentBeforeClose").AddEventHandler(this,Delegate.CreateDelegate(ty,开发者_运维技巧 this, "test",false));

test just pops up a messagebox.

Does anyone know why this is happening.


Can't test code right now, but what if use

this.Application.GetType().GetEvent("DocumentBeforeClose").AddEventHandler(this.Application,Delegate.CreateDelegate(ty, this, "test",false));

See this.Application instead of this in AddEventHandler call.

UPDATE: Now I can test the code and it works fine without exceptions if change "this" to "this.Application" as I mentioned before. Here is a full code:

namespace WordTestAddin
{
    public partial class ThisAddIn
    {
        private void ThisAddIn_Startup(object sender, System.EventArgs e)
        {
          Type ty = this.Application.GetType().GetEvent("DocumentBeforeClose").EventHandlerType;
          var testDelegate = Delegate.CreateDelegate(ty, this, "test", false);
          this.Application.GetType().GetEvent("DocumentBeforeClose").AddEventHandler(this.Application, testDelegate);
        }

        void test(Word.Document Doc, ref bool Cancel)
        {
          System.Windows.Forms.MessageBox.Show("test");
        }

        private void ThisAddIn_Shutdown(object sender, System.EventArgs e)
        {
        }

        #region VSTO generated code

        private void InternalStartup()
        {
          this.Startup += new System.EventHandler(ThisAddIn_Startup);
          this.Shutdown += new System.EventHandler(ThisAddIn_Shutdown);
        }

        #endregion
    }
}

So ensure, that your "test" method has a valid signature. Also ensure, that "test" is the exact method name, not "Test" or something.

0

精彩评论

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