Visual Basic, C & C++
분류 Delphi

Edit에 수치값만 입력 가능하게(소수, 음수입력 가능) 자리수 제한

페이지 정보

본문

Edit컨트롤에 정수, 소수, 음수만을 입력할 수 있게 한다.
숫자의 자릿수를 설정하여 자릿수만큼만 입력할 수 있게 한다.



procedure TForm1.Edit1KeyPress(Sender: TObject; var Key: Char);
var
  iKey : Integer;
  iPos : Integer;
  iLen : integer;
  iSel : integer;
  iAfterPointDigit :integer;
  iBeforePointDigit :integer;
  sText : string;
begin
  sText := Edit1.text;
  iKey := ord(Key);
  iLen := Length(trim(sText));
  iSel := Edit1.SelStart;
  iAfterPointDigit := 3;
  iBeforePointDigit := 3;

  if iKey = $08 then exit;  // Back space

  // 수치와 소숫점과 마이너스만 입력 가능하게
  if not(iKey in [$2E, $2D, $30..$39]) then begin Key := #0; exit; end;

  iPos :=  Pos('-', sText);
  // 마이너스가 두개 입력되지 않게
  if (iPos > 0) and (iKey = $2D) then begin Key := #0; exit; end
  else if (iPos = 0) and (iKey = $2D) and (iSel > 0) then
    begin Key := #0; exit; end;

  iPos :=  Pos('.', sText);
  // 소숫점 두개 안들어가게
  if (iPos <> 0) and (iKey = $2E) then begin Key := #0; exit;  end
  // 숫자가 입력되지 않았을 때, 소수점 입력 안되게
  else if (iPos = 0) and (iKey = $2E) and (iLen = 0) then
    begin Key := #0; exit; end;

  // 소수점 있을 때 소수점 앞의 자릿수 제한
  if (iPos > 0 ) then
  begin
    if ((iLen - iPos - 1) > (iBeforePointDigit - 1)) then
      begin Key := #0; exit; end;
  end
  // 소수점 없을 때 소수점 앞의 자릿수 제한
  else
  begin
    if (iLen > iBeforePointDigit - 1) and (iKey <> $2E) then
      begin Key := #0; exit; end;
  end;

  // 소숫점 뒤의 자리수 제한
  if (iPos > 0 ) and ((iPos + iAfterPointDigit - 1) < iLen) then
    if iSel > iPos then begin Key := #0; exit; end;
end;

관련자료

등록된 댓글이 없습니다.
프로그래밍
Today's proverb
행복은 뭘까? 우리와 함께하는 것들. 숨쉬는 공기, 나무, 하늘, 가족, 친구. 이에 대한 고마움은 스쳐지나가기가 쉽다. 행복은 우리와 함께하는 것들의 가치를 아는 것이다. (신현림)