How to set arbitrary type event handlers with RTTI in Delphi 2010?

after reading the message How to install event handlers through the new RTTI? , I wonder if this can be solved more dynamically. For example, I want to set ALL event handlers of any component to nil.

Using TValue.From <TNotifyEvent> (SomeMethod) does not work for two reasons: 1. The type is unknown (maybe TNotifyEvent, TMouseEvent, etc.) 2. I can not set "SomeMethod" to nil (invalid listing)

In the old RTTI style, I would do something like:

 var NilMethod: TMethod; begin [...] NilMethod.Data := nil; NilMethod.Code := nil; SetMethodProp (AComponent,PropertyName,NilMethod); 
+2
source share
1 answer

The following code should work:

 procedure NilAllEventHandlers(myObject: TObject); var context: TRttiContext; rType: TRttiType; field: TRttiField; value: TValue; nilMethod: TMethod; begin nilMethod.Code := nil; nilMethod.Data := nil; context := TRttiContext.Create; rType := context.GetType(TButton); for field in rType.GetFields do begin if field.FieldType.TypeKind = tkMethod then begin TValue.Make(@nilMethod, field.FieldType.Handle, value); field.SetValue(myObject, value); end; end; end; 

But this does not happen because in TValue.TryCast an error occurs when working with the value of TMethod, whose .Code parameter is nil . I will report this to QC. Hope it will be fixed in D2011 or updated. Until then, try the old style.

EDIT: displayed as QC # 81416 . Vote if you want this to be fixed.

+8
source

Source: https://habr.com/ru/post/1300406/


All Articles