我们要编写的程序很简单,在onKeyPress事件中,Key参数是一个字符,这样我们就可以在在onKeyPress事件中过滤掉用户所输入的字符。
因此我们要实现楼主位所需要的代码非常简单,只需要在在onKeyPress事件中加入如下代码即可:- if not ( Key in ['0'..'9','.',#8] ) then
- Key := #0;
复制代码 完整的onKeyPress事件代码如下:- procedure TForm2.输入KeyPress(Sender: TObject; var Key: Char);
- begin
- if not ( Key in ['0'..'9','.',#8] ) then
- Key := #0;
- end;
复制代码 这个程序的意思是当Key的字符不是0-9、'.'或退格键时将Key改为“#0”,也就是说将用户输入的除上述字符外都给过滤了。
直接将工程编译运行F9即可,这时编辑框只能输入0-9、'.'或退格键了。
如果把代码改成下面则只能输入0-9的数字字符- procedure TForm2.输入KeyPress(Sender: TObject; var Key: Char);
- begin
- if not ( Key in ['0'..'9','.',#8] ) then
- Key := #0;
- end;
复制代码 如果要限制输入框只能输入十六进制数的字符,则改成:- procedure TForm2.输入KeyPress(Sender: TObject; var Key: Char);
- begin
- Key := UpCase(Key);
- if not ( Key in ['0'..'9','A'..'F',#8] ) then
- Key := #0;
- end;
复制代码 |