2011-08-23 100 views
1

我有一個關於事件攔截與C#和Postsharp的問題。Postpost第三方組件事件攔截

我想在Postsharp中取消BeforeDropDown,RowSelected MouseClick和EventInterceptionAspect等事件的執行。

但我找不到合適的地方,我可以寫代碼。 例如:

我想是這樣的:

[Serializable] 
class EventInter : EventInterceptionAspect 
{ 
    public override bool CompileTimeValidate(System.Reflection.EventInfo targetEvent) 
    { 
     return "FormClosed".Equals(targetEvent.Name); 
    } 

    public override void OnInvokeHandler(EventInterceptionArgs args) 
    { 
     if condition executes method otherwise no 
    } 
} 

形式:

[EventInter] 
public partial class Frm_RomperMesa : KryptonForm 

但didn't工作。所以我想知道是否有可能實現我想要的。

感謝advace。我希望清楚。

+0

什麼樣的控件?像telerik控件?爲什麼不自己處理這些事件呢? –

回答

0

是的,這是可能的。問題是,你正試圖將事件攔截方面應用到另一個程序集中定義的事件中,而這是你在代碼中無法完成的事件。你甚至不能覆蓋的事件,因爲它的安裝使用在設計代碼的基礎表格類型背後

this.FormClosing += new System.Windows.Forms.FormClosingEventHandler(this.Form1_FormClosing); 

,你將不得不修改大會做處理。使用下面的方面和環節修改

public class EventAspectProvider : TypeLevelAspect , IAspectProvider 
    { 
     public IEnumerable<AspectInstance> ProvideAspects(object targetElement) 
     { 
      Type t = (Type)targetElement; 

      EventInfo e = t.GetEvents().First(c => c.Name.Equals("FormClosing")); 

      return new List<AspectInstance>() { new AspectInstance(e, new EventInter()) }; 
     } 

    } 

    [Serializable] 
    public class EventInter : EventInterceptionAspect 
    { 

     public override void OnInvokeHandler(EventInterceptionArgs args) 
     { 
      int x = 0; 

      if (x > 0) //Do you logic here 
      { 
       args.ProceedInvokeHandler(); 
      } 
     } 
    } 

基本上它歸結爲修改System.Windows.Forms.dll的我不推薦。但是,如果它是其他第三方供應商庫,那就去做吧。

+0

非常感謝。 TypeLevelAspect有沒有其他的選擇?因爲我有一個comunity許可證,並且有一個錯誤,告訴我使用的是未許可的feactures。 –

+0

嘗試刪除typelevelaspect並只實現IAspectProvider。 –

0

解決方法是以相反方式進行:在掛鉤到事件的方法上使用方面,並在符合條件時取消方法的正常執行。這不會阻止事件表單被引發,但它會阻止執行事件處理代碼。

[EventInter] 
private void someForm_FormClosed(object sender, EventArg arg) {} 

我們在我們的項目中使用了這種方法。我們有幾個方面適用於事件處理方法(異常處理,遊標處理等)。

我們走得更遠一點,我們在彙編級應用這些方面,並且我們使用CompileTimeValide來識別事件處理方法的簽名。從理論上講,它不是100%可靠的,但迄今爲止我們還沒有發現這種方法存在任何問題。