7

所以我已经有代码了。但是当它运行时它不允许退格键,我需要它来允许退格键并删除空格键,因为我不想要空格。

procedure TForm1.AEditAKeyPress(Sender: TObject; var Key: Char);
var s:string;
begin
s := ('1 2 3 4 5 6 7 8 9 0 .'); //Add chars you want to allow
if pos(key,s) =0 then begin Key:=#0;
showmessage('Invalid Char');
end;

需要帮助谢谢 :D

4

3 回答 3

9

请注意代码中已有的注释:

procedure TForm1.AEditKeyPress(Sender: TObject; var Key: Char);
var s:string;
begin
  s := ('1234567890.'#8); //Add chars you want to allow
  if pos(key,s) =0 then begin
    Key:=#0;
    showmessage('Invalid Char');
  end;
end;
于 2012-07-31T09:01:19.867 回答
5

最好将您的允许键作为常数(速度,优化)放在一组中:

更新 #2只允许一个十进制字符并正确处理 DecimalSeparator。

procedure TForm1.Edit1KeyPress(Sender: TObject; var Key: Char);
const
  Backspace = #8;
  AllowKeys: set of Char = ['0'..'9', Backspace];
begin
  if Key = '.' then Key := DecimalSeparator;
  if not ((Key in AllowKeys) or
    (Key = DecimalSeparator) and (Pos(Key, Edit1.Text) = 0)) then
  begin
    ShowMessage('Invalid key: ' + Key);
    Key := #0;
  end;
end;

为了获得更好的结果,请查看 DevExpress、JVCL、EhLib、RxLib 和许多其他库中包含的 TNumericEdit 组件。

于 2012-07-31T09:07:29.463 回答
1

使用通灵能力,我预测您正在尝试验证浮点值。

您可以使用控件的 OnExit 事件或表单的 Ok/Save 工具来检查正确的格式,如下所示:

procedure TForm1.Edit1Exit(Sender: TObject);
var
  Value: Double;
begin
  if not TryStrToFloat(Edit1.Text, Value) then begin
    // Show a message, make Edit1.Text red, disable functionality, etc.
  end;
end;

此代码假定您要使用特定于区域设置的小数分隔符。

如果您只想允许 a'.'您可以将TFormatSettings记录作为第三个参数传递给TryStrToFloat.

于 2012-07-31T15:30:49.557 回答