您的位置:首页 > 编程语言 > Delphi

Delphi中限制文本框(TEdit)只能输入小数

2009-04-10 14:08 393 查看
有些时候需要限制程序里的文本框(这里指TEdit控件)里只能输入某些特定字符。比如说限制只能输入数字,这时可以设置
TEdit的NumbersOnly属性来实现,这里的TEdit将被限制为只能输入0到9这十个字符。那么,如果需要限制输入小数呢,
小数点被阻止了,所以这时不能使用NumbersOnly属性,另外也没有别的属性能实现的。那就只有自己来做!

限制输入,可以在OnKeyPress事件中来做。见如下代码:

procedure TForm1.Edit1KeyPress(Sender: TObject; var Key: Char);
var
edt: TEdit;
str: string;
strL: string;
strR: string;
begin
// 获取当前文本内容, 注意要去掉选中部分(因为会被改写).
edt := TEdit(Sender);
str := edt.Text;
if Length(edt.SelText) <> 0 then
begin
strL := LeftStr(edt.Text, edt.SelStart);
strR := RightStr(edt.Text, Length(edt.Text) - edt.SelStart - edt.SelLength);
str := strL + strR;
end;

// 限制输入数字/小数点/退格键
if not CharInSet(Key, ['0'..'9', '.', #8]) then Key := #0;
// not (Key in ['0'..'9', '.', #8])

// 第一位不能为小数点
if (Key = '.') and (edt.SelStart = 0) then Key := #0;

// 只能输入一个小数点
if (Key = '.') and (Pos('.', str ) > 0) then Key := #0;

// 不能在前面插入 0 (输入第一个 0 时除外)
if (Key = '0') and (edt.SelStart = 0) and (str <> '') then Key := #0;

// 不能连续输入 0
if (Key = '0') and (LeftStr(str, 1) = '0') and (Pos('.', str) <= 0) then Key := #0;
end;以上考虑到了比较多的情况,可以很好的限制输入小数。如果程序里有很多的TEdit要做此限制,当然不必给每个控件写代码,把事件指定到同一个过程就行了。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: