这个符合你的要求,看一看吧
unit EditNum;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
StdCtrls;
type
TTextType=(tyNone,tyNumber,tyDecimal);
TEditNum = class(TEdit)
private
{ Private declarations }
FDecimal:integer;
FTextType:TTextType;
FKeyPress:TKeyPressEvent;
FOnExit:TNotifyEvent;
FNextObject:TWinControl;
FMaxLength:integer;
FAutoZero:Boolean;
protected
{ Protected declarations }
procedure KeyPress(var Key: Char); override;
procedure CMExit(var Message: TCMExit); message CM_EXIT;
public
{ Public declarations }
constructor Create(AOwer:TComponent);override;
destructor Destroy;override;
published
{ Published declarations }
property Decimal:integer read FDecimal write FDecimal;
property TextType:TTextType read FTextType write FTextType;
property OnKeyPress:TKeyPressEvent read FKeyPress write FKeypress;
property MaxLength:integer read FMaxLength write FMaxLength;
property NextObject:TWinControl read FNextObject write FNextObject;
property AutoZero:Boolean read FAutoZero write FAutoZero;
property OnExit:TNotifyEvent read FOnExit write FOnExit;
end;
procedure Register;
implementation
constructor TEditNum.Create(AOwer:TComponent);
begin
inherited Create(AOwer);
FDecimal := 2;
FTextType := tyNone;
MaxLength := 0;
FNextObject := NIL;
end;
destructor TEditNum.Destroy;
begin
inherited Destroy;
end;
procedure TEditNum.CMExit(var Message: TCMExit);
var i:integer;
begin
if FAutoZero then
if (FTextType <> tyNone) and (MaxLength <> 0) and (Length(Text) < MaxLength) then
for i := 1 to MaxLength-Length(Text) do begin
Text := '0'+Text;
end;
if Assigned(FOnExit) then FOnExit(Self);
end;
procedure TEditNum.KeyPress(var Key:Char);
var DecLoc:integer;
begin
if Key = #13 then begin
if FNextObject <> NIL then
if FNextObject.Visible then
FNextObject.SetFocus
else
if FNextObject is TEditNum then
TEditNum(FNextObject).NextObject.SetFocus;
end
else begin
if Length(SelText) = 0 then begin
if (Length(Text) >= MaxLength) and (MaxLength <> 0) then
if Key <> #8 then
Key := #0;
end;
case FTextType of
tyNumber: begin
if Key = '-' then begin
if (Pos('-',Text) <> 0) or (Length(Text) > 0) then
Key := #0;
end;
if not (Key in ['0'..'9',#8,'-']) then
Key := #0;
end;
tyDecimal: begin
DecLoc := Pos('.',Text);
if Key = '.' then begin
if DecLoc <> 0 then
Key := #0;
end
else begin
if Key = '-' then begin
if (Pos('-',Text) <> 0) or (Length(Text) > 0) then
Key := #0;
end;
if Key <> #8 then begin
if DecLoc <> 0 then
if (Length(Text) - DecLoc) >= 2 then
Key := #0;
if not (Key in ['0'..'9','-']) then
Key := #0;
end;
end;
end;
end;
end;
if Assigned(FKeyPress) then FKeyPress(self,Key);
end;
procedure Register;
begin
RegisterComponents('ActiveX', [TEditNum]);
end;
end.