VCL下可以在OnKeyPress事件下这样写
procedure TForm1.Edit1KeyPress(Sender: TObject; var Key: Char); begin if not (key in ['0'..'9','.',#8]) then key:=#0; if (key='.') and (Pos('.',TEdit(Sender).Text)>0) then //TEdit(Sender)写法,这段代码可以重用,不必在每个Edit下都写一段代码,其他Edit控件只要引用这个Edit的事件即可 key:=#0; end;
XE的FMX里没有OnKeyPress事件,所以在OnKeyDown下写,而Key参数是Word类型,所以要用到KeyChar
procedure TForm1.Edit1KeyDown(Sender: TObject; var Key: Word; var KeyChar: Char; Shift: TShiftState); var i: Boolean; begin i := (KeyChar <= #8) or (KeyChar <= #8) and (KeyChar < #48) or (KeyChar > #57); if i then KeyChar := #0; if not (KeyChar in ['0'..'9', '.', #13]) then KeyChar := #0; if (KeyChar = '.') and (Pos('.', TEdit(Sender).Text) > 0) then KeyChar := #0; end;