精华区 [关闭][返回]

当前位置:网易精华区>>讨论区精华>>编程开发>>● Delphi>>控件开发和使用>>创建一个只能录入浮点数的编辑框

主题:创建一个只能录入浮点数的编辑框
发信人: lihai155(天琴)
整理人: teleme(2001-01-03 15:23:11), 站内信件
unit FInput;

interface

uses
  Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
  StdCtrls;

type
  TFloatEdit = class(TEdit)
  private
    { Private declarations }
    Fracs:Integer;    //小数位数
    procedure MyChange(Sender:TObject);
    procedure MyKeyPress(Sender: TObject; var Key: Char);
    procedure SetFrac(const Value: Integer);
  protected
    { Protected declarations }
  public
    { Public declarations }
    Constructor Create(AOwner:TComponent);override;
    Destructor Destroy;override;
  published
    { Published declarations }
    property Frac:Integer Read Fracs Write SetFrac;
  end;

procedure Register;

implementation

procedure Register;
begin
  RegisterComponents('Samples', [TFloatEdit]);
end;

{ TEdit1 }

constructor TFloatEdit.Create(AOwner: TComponent);
begin
  inherited;
  OnChange:=MyChange;
  OnKeyPress:=MyKeyPress;
  Fracs:=2;
  Text:='0';
end;

destructor TFloatEdit.Destroy;
begin
  inherited;

end;

procedure TFloatEdit.MyChange(Sender: TObject);
begin
  if Parent=nil then exit;
  if Text = '' then exit;
  try
    if StrToFloat(Text)>922337203685477.5807 then
      Begin
        Application.MessageBox(PChar('数字太大。'),'错误',MB_OK);
        Text:='';
      End
  except
    Application.MessageBox(PChar('无效的数字。'),'错误',MB_OK);
    Text :='';
  End;
end;

procedure TFloatEdit.MyKeyPress(Sender: TObject; var Key: Char);
Var
  NewText:String;
begin
  if (Fracs=0) And (Key='.') then
    Begin
      Key:=#0;
      Exit;
    End;
  if Not(Key in ['0'..'9']) And (Key<>Chr(VK_BACK)) And (Key<>'.') then
    Begin
      Key:=#0;
      Exit;
    End;
  NewText:=Copy(Text,1,Self.SelStart-1)+Copy(Text,Self.SelStart+Self.SelLength,Length(Text));
  if (Pos('.',NewText)>0) And (Key='.') then
    Begin
      Key:=#0;
      Exit;
    End;
  NewText:=Copy(Text,1,Self.SelStart-1)+Key+Copy(Text,Self.SelStart+Self.SelLength,Length(Text));
  if (Pos('.',NewText)>0) And (Length(NewText) - Pos('.',NewText)>Fracs) And
    (Key in ['0'..'9']) then
    Begin
      Application.MessageBox(PChar('小数位数不能超过'+
        IntToStr(Fracs)+'位。'),'错误',MB_OK);
      Key:=#0;
    End;
end;

procedure TFloatEdit.SetFrac(const Value: Integer);
begin
  if Value<0 then
Application.MessageBox(PChar('小数位数不能为负数。'),'错误',MB_OK)
else
Fracs := Value;
end;

end.
//有什么改进意见欢迎回复,谢谢!


----
问彩云何处飞,愿成风永追随。
有奇缘能相聚,死也无悔。
我柔情深似海,你痴心可问天。
誓相守长缱绻,岁岁年年。

[关闭][返回]