[Lazarus] how to get Type of Sender or Components[i] in order to Cast?

Mark Morgan Lloyd markMLl.lazarus at telemetry.co.uk
Mon Jul 27 11:37:19 CEST 2015


JuuS wrote:
> On 07/27/2015 09:31 AM, Mark Morgan Lloyd wrote:
>> Péter Gábor wrote:
>>> Sorry!
>>> I was "misreading" your mail... you want to know the type of them.
>>>
>>> You can compare the type of them:
>>>
>>> if Sender = TButton then { do something} ;
>> Can this be elegantly put into a case statement?
>>
> Hi, I just tried it and no you can't. At least not directly, there may
> be a way of casting the Sender object to ordinal or string but I'm not
> sure that is efficient or elegant.

I didn't think there was, but thought it worth asking. My use case is 
this sort of thing:

         if MainForm.OutputComponent is TListBox then
           with MainForm.ListBox1 do begin
             Font.Name := fontName;
             Font.Size := fontSize
           end;
         if MainForm.OutputComponent is TMemo then
           with MainForm.Memo1 do begin
             Font.Name := fontName;
             Font.Size := fontSize
           end;
         ...

Now obviously I could have a separate property holding an enumeration, 
but it's a pity that it's not possible to do something like

         case MainForm.OutputComponent of
           TListBox: begin end;
           TMemo:    begin end;
           ...
         otherwise
           // Fatal exception since this is a serious programming error
         end;

-- 
Mark Morgan Lloyd
markMLl .AT. telemetry.co .DOT. uk

[Opinions above are the author's, not those of his employers or colleagues]




More information about the Lazarus mailing list