编辑框中只有特定数字

Only specific numbers in edit box

我希望用户只能在编辑框中输入 1 到 49 之间的数字。我知道如何排除字母并且有可能只输入数字但我不能将其限制为特定数字(例如从 1 到 49 - 就像在彩票游戏中一样)。 我将 KeyDown 事件添加到编辑框并输入以下代码:

   if not (KeyChar in ['1'..'9']) then
   begin
      ShowMessage('Invalid character');
      KeyChar := #0;
   end;

如何修改?

按照 David 的建议,我经常使用的模式如下所示:

function Validate1To49(AStr : string; var Value : integer) : boolean;
begin
  result := TryStrToInt(AStr, Value) and
            (Value >= 1) and (Value <= 49);
end;

procedure TForm1.Edit1Change(Sender: TObject);
var
  tmp : integer;
begin
  if Validate1To49(Edit1.Text, tmp) then
    Edit1.Color := clWhite
  else
    Edit1.Color := clRed;
end;

procedure TForm1.Button1Click(Sender: TObject);
var
  theValue : integer;
begin
  if Validate1To49(Edit1.Text, theValue) then begin
    // go ahead and do something with "theValue"
  end else
    ShowMessage('Value not valid');
end;   

在这里,如果用户输入任何无效内容,就会有即时的视觉反馈,不像模态消息框那样具有干扰性。在这里,我将编辑框涂成红色,但您也可以 show/hide 或更改编辑框上方警告标签的颜色,其中包含详细说明预期输入的消息、使用绿色复选标记或其他任何合理的方式

这样做的好处是用户可以立即看到他们的输入是否有效。可以包装验证方法,以便在用户尝试启动需要这些输入的操作时可以重新使用它们。在这一点上,我觉得使用模态消息框很好,因为用户显然错过了已经摆在他们面前的明显提示。或者,在 OnChange 处理程序中验证时,您可以简单地禁用任何允许用户继续的操作控件(如按钮等)。这需要验证操作所需的所有输入控件 - 同样,通常您会将整个验证操作包装到一个方法中以便合理地重用。

对于像整数这样的简单值,一个好的 SpinEdit 控件可能会有用(VCL 控件包含在示例包中 - 默认情况下并不总是安装)。然而,上述模式更灵活,可用于任何类型的输入。然而,SpinEdit 不会提供任何反馈 - 用户将只是键入而不会显示任何内容。如果没有关于输入元素将接受什么的明确指导,他们可能想知道应用程序是否已损坏。

同样的问题也可以通过为编辑框编写 OnKeyPress 事件来以这种方式回答。通过这种方式,用户将无法输入大于我们定义的限制的数字。

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;