C++Builder 2009からTEditにAlignmentが追加されました。
AlignmentプロパティをtaRightJustifyに設定することで、右寄せ表示ができます。
Edit1->Alignment = taRightJustify;
Windows XP以降なら、SetWindowLong()を使うことで簡単に実現できます。
Unit1.cpp
__fastcall TForm1::TForm1(TComponent* Owner)
: TForm(Owner)
{
::SetWindowLong(Edit1->Handle,
GWL_STYLE,
::GetWindowLong(Edit1->Handle, GWL_STYLE) | ES_RIGHT);
}
以上で、Edit1は右寄せで表示されるようになります。
Windows XP以前の場合は、右寄せ表示する専用のコンポーネントを作成します。
TRightEdit.h
//---------------------------------------------------------------------------
#ifndef TRightEditH
#define TRightEditH
//---------------------------------------------------------------------------
#include <vcl.h>
//---------------------------------------------------------------------------
class TRightEdit : public TEdit
{
protected:
void __fastcall CreateParams(TCreateParams& Params);
};
#endif
TRightEdit.cpp
#pragma hdrstop
#include "TRightEdit.h"
//---------------------------------------------------------------------------
#pragma package(smart_init)
void __fastcall TRightEdit::CreateParams (TCreateParams& Params)
{
TEdit::CreateParams(Params);
Params.Style |= ES_RIGHT;
}
作成したコンポーネントをツールパレットに登録して使用すればいいのですが、コンポーネントとして登録したくない、あるいは、すでにフォームにたくさんのEditコンポーネントを貼り付けているので置き換えたくない場合もあると思います。
その場合は、「コード倉庫/コンポの付け替え」で紹介されている ChangeComponent() を使用します。
UnitChangeComponent.pas
interface
uses
Classes;
function ChangeComponent(old: TComponent; NewClass: TComponentClass): TComponent;
implementation
uses
TypInfo, Controls;
function ChangeComponent(old: TComponent; NewClass: TComponentClass): TComponent;
var
new: TComponent;
Stream: TStream;
Methods: array of TMethod;
aPPropInfo: array of PPropInfo;
cnt, i: Integer;
begin
SetLength(aPPropInfo, 16379);
cnt := GetPropList(old.ClassInfo, [tkMethod], @aPPropInfo[0]);
SetLength(Methods, cnt);
for i := 0 to cnt - 1 do Methods[i] := GetMethodProp(old, aPPropInfo[i]);
Stream := TMemoryStream.Create;
try
Stream.WriteComponent(old);
new := NewClass.Create(old.Owner);
if new is TControl then TControl(new).Parent := TControl(old).Parent;
Stream.Position := 0;
old.Free;
Stream.ReadComponent(new);
finally Stream.free end;
for i := 0 to cnt - 1 do SetMethodProp(new, aPPropInfo[i], Methods[i]);
Result := new;
end;
end.
Unit1.cpp
#include "UnitChangeComponent.hpp"
#include "TRightEdit.cpp"
__fastcall TForm1::TForm1(TComponent* Owner)
: TForm(Owner)
{
Edit1 = (TEdit*)ChangeComponent(Edit1, __classid(TRightEdit));
}
これでフォームに貼り付けたコンポーネントEdit1が右寄せ表示Editコントロール TRightEdit に置き換えられ、右寄せ表示されるようになります。