none
Adding a delegate to an eventhandler RRS feed

  • Question

  • H

    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.

    Thanks

    Beats

    Monday, February 7, 2011 2:10 PM

Answers

  • Hi Esters

    I believe the problem was that the signature of the test method I was calling was completely wrong.

    as answered here: http://stackoverflow.com/questions/4922319/adding-a-delegate-to-an-eventhandler

    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");     
    }
    

     Thanks

    • Marked as answer by beats Wednesday, February 9, 2011 12:13 PM
    Wednesday, February 9, 2011 12:12 PM

All replies

  • Delegate.CreateDelegate method has Type parameter as its first parameter. It means to represent the type of delegate to create.

    I think this question is you need to create a non-static method delegate, you must give the reference to the object the method belongs to.

    More information about this method you can check here.

    Thanks,

    Esters

    Tuesday, February 8, 2011 5:27 AM
  • Hi Esters

    I believe the problem was that the signature of the test method I was calling was completely wrong.

    as answered here: http://stackoverflow.com/questions/4922319/adding-a-delegate-to-an-eventhandler

    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");     
    }
    

     Thanks

    • Marked as answer by beats Wednesday, February 9, 2011 12:13 PM
    Wednesday, February 9, 2011 12:12 PM