我一直这么用,没问题。 procedure Tform1.Edit1KeyPress(Sender: TObject; var Key: Char); begin if key in ['1','2','3','4','5','6','7','8','9','0','.',#8] then begin end else begin if key=#13 then Edit1.SetFocus else key:=#0; //过滤掉其他的输入 end; end; 除了数字和点以及删除键,其他的全部过滤。 在说数字输入的edit很多呀。(比如rxlib的)另:你的ascii表示有问题。应该是[#48..#57]
haha:上面的程序有一个小问题: if key=#13 下一个控件.setfocus else ...
///处理字符窜
else
///处理数字;
说明: 首先需要用户不会输入-9999,否则需要换一个数
MaskEdit控件的EditMask属性就是管这个事儿的
选错了事件,
procedure (Sender: TObject; var Key: Word; Shift: TShiftState) of object;
OnKeyDown Key : word;
procedure (Sender: TObject; var Key: Char) of object;
OnKeyPress Key : Char
StrToInt你判断一下嘛,Edit.Text = ''就什么都不作.
i:=StrToInt(Edit1.Text);
是整数,这里做你的处理
except
//不是整数
ShowMessage("您输入的不是整数,请重新输入!");
Edit1.Text:='';
Edit1.SetFocus;
end;
procedure Tform1.Edit1KeyPress(Sender: TObject; var Key: Char);
begin
if key in ['1','2','3','4','5','6','7','8','9','0','.',#8] then
begin
end else
begin
if key=#13 then Edit1.SetFocus else
key:=#0; //过滤掉其他的输入
end;
end;
除了数字和点以及删除键,其他的全部过滤。
在说数字输入的edit很多呀。(比如rxlib的)另:你的ascii表示有问题。应该是[#48..#57]
if key=#13 下一个控件.setfocus else ...
#48..#57实际上等同于'0'..'9'。有一件事我还不明白,keyexit是什么事件,我怎么没见过?好象只有OnExit吧。
Delphi中没有提供判断是否数字串的函数,可以用StrToInt或StrToIntDef做一个,或干脆就一个字符一个字符地判断,但还得判断是否超界,很麻烦。用StrToIntDef时,可以将默认值设为一个空白值:Integer($80000000),这样就不用担心是否与正常使用值冲突了。
如果输入的可能是小数,那么用key in '1','2','3','4','5','6','7','8','9','0','.',#8] 也是不够的,否则我输入
'-100'不能通过,输入'100.01.02',却能通过!
unit DigitEdit;interfaceuses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
StdCtrls;const
DIGITS = [^H, '0'..'9'];
type
TDigitEdit = class(TEdit)
private
fChr : Char;
{ Private declarations }
protected
procedure Change; override;
procedure SetChr(Value : char);
{ Protected declarations }
public
constructor Create(AOwner : TComponent); override;
destructor Destroy; override;
procedure CreateParams(var Params:TCreateParams);override;
{ Public declarations }
published
property Chr : Char read fChr write SetChr default #0;
{ Published declarations }
end;procedure Register;implementationprocedure TDigitEdit.CreateParams(var Params: TCreateParams);
begin
inherited CreateParams(Params);
Params.Style:= Params.Style or ES_RIGHT;
end;procedure TDigitEdit.SetChr(Value : char);
begin
if fChr <> value then fChr := Value;
end;constructor TDigitEdit.Create(AOwner : TComponent);
begin
inherited Create(AOwner);
end;Destructor TDigitEdit.Destroy;
begin
inherited Destroy;
end;procedure TDigitEdit.Change;
var
i, Posi : Integer;
aText : string;
begin
inherited Changed;
if csDesigning in ComponentState then Exit;
aText := Text;
Posi := SelStart;
for i := 1 to Length(aText) do
if not ((aText[i] in DIGITS) or (aText[i] = fChr))then
Delete(aText, i, 1);
Text := aText;
// SelStart := Length(Text);
SelStart := Posi;
end;procedure Register;
begin
RegisterComponents('Standard', [TDigitEdit]);
end;end.