c++buildervcltaction

How to cast to TMenuItem in TActions Execute method?


I have a number of related TMenuItems, in a CodeGear C++ VCL application.

Each TMenuItem is associated to the same action (TAction).

When a MenuItem is clicked, the action fires (its execute method that is).

I will need to, somehow, cast the Sender parameter in the actions OnExecute function to figure out which menuitem that was clicked.

Currently I have something like this

void __fastcall TMoleculixDesktopMainUnit::openMoleculeSelectionFormAExecute(TObject *Sender)
{
//User selected a menuitem under Molecules Menu

TAction* anItem = dynamic_cast<TAction*>(Sender);


//AminoAcidsMI is a TMenuItem
if(AminoAcidsMI == dynamic_cast<TMenuItem*>(anItem->Owner))
{
    //Open molecule search form with aminoacids
    MLog()<<"Looking for Amino Acids..";
}
}

But the above does not work The actions Owner is NOT the MenuItem.


Solution

  • Use the TAction::ActionComponent property, which specifies the component that triggered the action.

    void __fastcall TMoleculixDesktopMainUnit::openMoleculeSelectionFormAExecute(TObject *Sender)
    {
        //User selected a menuitem under Molecules Menu
    
        TAction* anItem = dynamic_cast<TAction*>(Sender);
        if (!anItem) return;
    
        AminoAcidsMI == dynamic_cast<TMenuItem*>(anItem->ActionComponent);
        if (AminoAcidsMI)
        {
            //Open molecule search form with aminoacids
            MLog()<<"Looking for Amino Acids..";
        }
    }