views:

229

answers:

1

Hi,

after reading the post How to set event handlers via new RTTI?, I wonder if it is possible to solve this 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 (could be TNotifyEvent, TMouseEvent etc.) 2. I cannot set 'SomeMethod' to nil (invalid cast)

In old RTTI style I would do something like:

var
  NilMethod: TMethod;
begin
[...]
NilMethod.Data := nil;
NilMethod.Code := nil;
SetMethodProp (AComponent,PropertyName,NilMethod);
+6  A: 

The following code ought to 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 it doesn't because there's a bug in TValue.TryCast when working with a TMethod value whose .Code parameter is nil. I'll report it to QC. Hopefully it'll get fixed in D2011 or an update. Until then, try the old style.

EDIT: Reported as QC# 81416. Vote it up if you want to see it fixed.

Mason Wheeler
+1; for the try. voted for getting it fixed.
Jeroen Pluimers