Delphi - 在按键事件中制作一个编辑框以仅接受小于或等于 (<=) 12 的数字



我有一个编辑框,我试图使它只接受从0到12的数字。我写了一个onExit处理程序,像这样:

procedure TfrmCourse.edtDurationExit(Sender: TObject);
begin
     if not string.IsNullOrEmpty(edtDuration.Text) then
          begin
            if StrToInt(edtDuration.Text) > 12 then
            begin
              edtDuration.Clear;
              edtDuration.SetFocus;
            end;
          end;
end;

…但是我想在输入时检查这个。TEdit应该只接受数字输入,并在值> 12时发出警告。

我对这个问题的回答是

最终答案

procedure TfrmCourse.edtDurationKeyPress(Sender: TObject; var Key: Char);
var
  sTextvalue: string;
begin
  if Sender = edtDuration then
  begin
    if (Key = FormatSettings.DecimalSeparator) AND
      (pos(FormatSettings.DecimalSeparator, edtDuration.Text) <> 0) then
      Key := #0;
    if (charInSet(Key, ['0' .. '9'])) then
    begin
      sTextvalue := TEdit(Sender).Text + Key;
      if sTextvalue <> '' then
      begin
        if ((StrToFloat(sTextvalue) > 12) and (Key <> #8)) then
          Key := #0;
      end;
    end
  end;
end;

如果输入的字符不是数字,则转换函数StrToInt()引发一个EConvertError。您可以通过设置TEdit.NumbersOnly属性来解决这个问题。我建议使用TryStrToInt()函数代替(或添加)。虽然你说你想检查,而键入我也建议使用OnChange事件,因为它也捕获错误的输入粘贴从剪贴板。

procedure TForm5.Edit1Change(Sender: TObject);
var
  ed: TEdit;
  v: integer;
begin
  ed := Sender as TEdit;
  v := 0;
  if (ed.Text <> '') and
    (not TryStrToInt(ed.Text, v) or (v < 0) or (v > 12)) then
  begin
    ed.Color := $C080FF;
    errLabel.Caption := 'Only numbers 0 - 12 allowed';
    Exit;
  end
  else
  begin
    ed.Color := clWindow;
    errLabel.Caption := '';
  end;
end;

errLabel是编辑框附近的一个标签,用于提示用户输入错误。

最新更新