VCL 에디트(TEdit)의 NumbersOnly 속성을 이용하면 컨트롤에 숫자만 입력받도록 구현할 수 있다는 것 잘 아실텐데요.이번 글에서는 숫자 입력 시 콤마를 자동추가할 수 있도록 구현한 내용 공유합니다.
기능은 2가지입니다.
- 키입력 시 3자리마다 콤마 추가(e.g. 123,456,789,012)
- 에디트에서 순수 숫자만 읽고 쓰기(PlainText 속성 추가)
구현은 여러폼에서 uses에 추가하기만 하면 동작하도록 별도의 유닛으로 만들었습니다.
unit Vcl.EditExtends;
interface
uses
Vcl.StdCtrls, Vcl.Controls, System.Classes;
type
TEdit = class(Vcl.StdCtrls.TEdit)
private
function GetPlainText: string;
procedure SetPlainText(const Value: string);
protected
procedure KeyUp(var Key: Word; Shift: TShiftState); override;
public
property PlainText: string read GetPlainText write SetPlainText;
end;
implementation
uses
SysUtils;
{ TEditEx }
procedure TEdit.KeyUp(var Key: Word; Shift: TShiftState);
var
S: string;
begin
inherited;
S := Text;
S := S.Replace(',', '').Replace('.', '');
Text := FormatFloat('#.###,##', StrToFloatDef(S, 0));
selStart := Length(Text) + 1;
end;
function TEdit.GetPlainText: string;
var
S: string;
begin
S := Text;
Result := S.Replace(',', '').Replace('.', '');
end;
procedure TEdit.SetPlainText(const Value: string);
var
Key: Word;
begin
Text := Value;
KeyUp(Key, []);
end;
end.사용법은
- 폼에 Edit 컴포넌트를 추가하고 Vcl.EditExtends를 상단(interface) uses 절에 추가합니다.(Vcl.StdCtrls 뒤에 Vcl.EditExtends가 추가되야 합니다.)
- 키입력시 콤마 추가는 자동으로 동작합니다.
- 순수 숫자 넣고 읽기는 PlainText 메소드를 이용할 수 있습니다.
기타 필요한 기능 추가해서 사용하시기 바랍니다.(알려주시면 기능을 추가해서 올리겠습니다.)
NumbersOnly.zip