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要做此限制,当然不必给每个控件写代码,把事件指定到同一个过程就行了。
相关文章推荐
- Delphi中限制文本框(TEdit)只能输入数字
- Delphi中限制文本框(TEdit)只能输入数字
- Delphi中限制文本框(TEdit)只能输入数字
- JQuery 正则 限制文本框(input)只能输入数字/限制输入金额为两位小数
- js限制文本框只能输入整数或者带小数点的数字
- 自己写的 限制文本框TEdit中只能输入数字
- asp.net中前台限制TextBox文本框只能输入数字和小数(或数字和字母)
- Javascript验证和限制文本框只能输入数字或者小数
- 限制文本框只能输入正数,负数,小数
- jquery封装 [ 限制文本框只能输入数字和小数] 语句,简单调用即可
- JS限制文本框只能输入整数或小数
- 用JS限制文本框只能输入数字时的正则表达式问题!
- 从别人那看到的 js正则表达式限制文本框只能输入数字,小数点,英文字母
- js正则表达式限制文本框只能输入数字,小数点,英文字母,汉字等各类代码
- JS限制文本框输入金额并保留两位小数
- 文本框只能输入小数
- js正则表达式限制文本框只能输入数字,小数点,英文字母
- 正则表达式限制文本框只能输入数字
- C#Winform限制TextBox文本框只能输入文本的格式
- js限制文本框input只能输入数字