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.
精彩评论