0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

C++ Builder XE4, 10.2 Tokyo > HWNDの取り方 > リファクタリング対応

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

はまったこと

  1. HWND型変数にFindWindowEx()にて値を代入
  2. その対象となるフォームの名前を変更した (xxxFormからFormXXX)
  3. HWND型変数がNULLになる
  4. NULLのまま処理をされ、別の処理でのNULLチェックにひっかかりエラーが出た

希望

フォーム名を変更した時に、ビルド処理でエラーの原因を明示したい。

実装

  • 構成
    • Form1 (Unit1.cpp)
    • Form2 (Unit2.cpp)
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::Button1Click(TObject *Sender)
{
	// Case 1
	String fullCaption = L"Form2";

	HWND subHwnd = FindWindowEx(NULL, NULL, NULL, fullCaption.c_str());
}
//---------------------------------------------------------------------------
void __fastcall TForm1::Button2Click(TObject *Sender)
{
	// Case 2
	String fullCaption = Form2->Caption;

	HWND subHwnd = FindWindowEx(NULL, NULL, NULL, fullCaption.c_str());
}
//---------------------------------------------------------------------------

上記のCase 2にすることで、「フォーム名の変更時」にビルドエラーが出てくれ、間違いに気づきやすい。

pros and cons

  • Case 1
    • 利点: #include "Unit2.h"が不要
    • 欠点: フォーム名変更時に失敗に気づきにくい
  • Case 2
    • 利点: フォーム名変更時に失敗に気づく
    • 欠点: #include "Unit2.h"が必要
      • 依存関係が生まれるが、Form2のコンポーネントを使っている時点で依存関係はある

備考

FindWindowEx()を使わずにForm2からHWNDを取る方法はあるかもしれない(未調査)

Case 3

Case 2の処理は以下でよかった。

Unit1.cpp
void __fastcall TForm1::Button3Click(TObject *Sender)
{
	// Case 3
	HWND subHwnd = Form2->Handle;
}

FindWindowEx()は不要。

0
1
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
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?