본문 바로가기
Delphi Tip/컴포넌트

TEdit 숫자만 입력받기

by MonoSoft 2021. 10. 27.
728x90
반응형

TEdit 숫자만 입력받기

 

 

procedure TForm1.Edit1KeyPress(Sender: TObject; var Key: Char);

begin

// #8 is Backspace

if not (Key in [#8, '0'..'9']) then begin

ShowMessage('Invalid key');

// Discard the key

Key := #0;

end;

end;

 

If you also want numbers with a decimal fraction, you must allow a POINT or a COMMA, but only once. For an

international version that looks at the correct decimal separator, he code could be as follows:

 

procedure TForm1.Edit1KeyPress(Sender: TObject; var Key: Char);

begin

if not (Key in [#8, '0'..'9', DecimalSeparator]) then begin

ShowMessage('Invalid key: ' + Key);

Key := #0;

end

else if (Key = DecimalSeparator) and

(Pos(Key, Edit1.Text) > 0) then begin

ShowMessage('Invalid Key: twice ' + Key);

Key := #0;

end;

end;

 

And here's a full blown version of the event handler, accepting a decimal separator and negative numbers (the minus

sign is only accepted once and it has to be the first character):

 

procedure TForm1.Edit1KeyPress(Sender: TObject; var Key: Char);

begin

if not (Key in [#8, '0'..'9', '-', DecimalSeparator]) then

ShowMessage('Invalid key: ' + Key);

Key := #0;

end

else if ((Key = DecimalSeparator) or (Key = '-')) and 

(Pos(Key, Edit1.Text) > 0) then begin

ShowMessage('Invalid Key: twice ' + Key);

Key := #0;

end

else if (Key = '-') and 

(Edit1.SelStart <> 0) then begin

ShowMessage('Only allowed at beginning of number: ' + Key);

Key := #0;

end;

end;

 

728x90
반응형

'Delphi Tip > 컴포넌트' 카테고리의 다른 글

[Controls] EDIT에 숫자만 입력받기  (0) 2021.11.02
TXMLDocument를 이용한 XML로딩방법  (0) 2021.11.01
TList 활용하기  (0) 2021.10.29
TEdit 다음 포커스 이동하기  (0) 2021.10.28
TdateEdit 날짜 요일 구하기  (0) 2021.10.26

댓글