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;

관련자료

댓글 0
등록된 댓글이 없습니다.
Today's proverb
우리의 꿈은, 뒤에 오는 사람들이 우리를 딛고 우리 위에서 이루게 하는 것입니다. 나는 평생을 창조적인 작업을 위해서 살아왔습니다. 누가 하라고 해서 한 것이 아니라 그것이 나의 삶 그 자체의 즐거움이었기 때문입니다. 현실을 직시하며 현재의 수준을 유지하라. 그리고 더 먼 곳을 향하는 시야를 가져라.