ボタンを押したとき、関連づけられたアクションから実行したボタンを取得する

アクションをボタンに関連づけていると、ボタンを押したときに実行されるイベントの引数Senderがボタンに関連づけられたアクションになります。

void __fastcall TForm1::Action1Execute(TObject *Sender)
{
  TAction* action = static_cast<TAction*>(Sender);

アクションを実行したコンポーネントは、TActionのActionComponentで取得することができます。

  TAction* action = static_cast<TAction*>(Sender);
  TComponent* component = action->ActionComponent;

アクションを実行したコンポーネントを取得したら、ボタンにキャストします。

  TComponent* component = action->ActionComponent;
  TButton* button = static_cast<TButton*>(component);

次のサンプルプログラムでは、押したボタンの名前を表示します。

フォームにTButtonを2つとTActionManagerを配置します。

ActionManager1にアクションを追加します。

追加したアクションのOnExecuteメソッドを実装します。

void __fastcall TForm1::Action1Execute(TObject *Sender)
{
  TAction* action = static_cast<TAction*>(Sender);
  TComponent* component = action->ActionComponent;
  TButton* button = static_cast<TButton*>(component);
  ShowMessage(button->Name);
}

2つのボタンのActionプロパティに、先ほどを作成したアクションを設定します。

プログラムを実行します。

ボタンを押すと、押したボタンの名前が表示されます。

FireMonkeyアプリケーションでも同じように動作しました。

コメントを残す

メールアドレスが公開されることはありません。 が付いている欄は必須項目です

このサイトはスパムを低減するために Akismet を使っています。コメントデータの処理方法の詳細はこちらをご覧ください