LoginSignup
0
0

More than 5 years have passed since last update.

C++ Builder XE4, 10.2 Tokyo > Form2のTButton::OnClickイベントをForm1のTButtonで使う

Last updated at Posted at 2017-11-07
動作環境
C++ Builder XE4
RAD Studio 10.2 Tokyo Update 2 (追記: 2018/01/05)

Form2でOnClickを実装しているTButtonがあるとする。
Form1のTButtonをクリックした時にそのイベント処理をする。

code

Unit1.cpp
//---------------------------------------------------------------------------

#include <vcl.h>
#pragma hdrstop

#include "Unit1.h"
#include "Unit2.h"
//---------------------------------------------------------------------------
#pragma package(smart_init)
#pragma resource "*.dfm"
TForm1 *Form1;
//---------------------------------------------------------------------------
__fastcall TForm1::TForm1(TComponent* Owner)
    : TForm(Owner)
{
}

void __fastcall TForm1::FormShow(TObject *Sender)
{
    Form1->Button1->OnClick = Form2->Button1->OnClick;
}
//---------------------------------------------------------------------------
Unit2.cpp
//---------------------------------------------------------------------------

#include <vcl.h>
#pragma hdrstop

#include "Unit2.h"
//---------------------------------------------------------------------------
#pragma package(smart_init)
#pragma resource "*.dfm"
TForm2 *Form2;
//---------------------------------------------------------------------------
__fastcall TForm2::TForm2(TComponent* Owner)
    : TForm(Owner)
{
}
//---------------------------------------------------------------------------
void __fastcall TForm2::Button1Click(TObject *Sender)
{
    ShowMessage(L"Form2");
}
//---------------------------------------------------------------------------

備考

以下のタイミングでのForm1->Button1->OnClick代入は失敗する。

  • Form1のコンストラクタ
  • Form1のOnCreate

Form2の生成タイミングによると思われる。
Form1のOnShowであれば、Form2は生成済みだろう。

用途

一つのフォームで多くの処理を実装したとき、コードの可読性が悪くなる (例: 1390行のコード、40弱の関数)。
将来の機能追加、バグ修正に負担が生じる。

上記のように別ユニットでの実装にして利用すると、フォームの可読性が良くなる経験をしている。
「1つの装置」の処理を「別の装置」の処理に置換えしやすくもなる。
(処理の分離方法は他にもあるだろう。)

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0