【问题标题】:How can I change the TEdit default error message (NumbersOnly mode)?如何更改 TEdit 默认错误消息(NumbersOnly 模式)?
【发布时间】:2024-01-07 23:29:01
【问题描述】:

当我在NumbersOnly 模式下使用 TEdit 时,如何更改它的默认错误消息。我的意思是这个错误:

不可接受的字符您只能在此处输入数字

是否可以更改此消息?

【问题讨论】:

  • 正如 Nat 所写,这条消息似乎来自操作系统,而不是来自 VCL。这并不意味着您将无法捕捉到它,但我在文档上注意到了这一点:“但是请注意,即使设置了此属性,用户也可以在文本字段中粘贴非数字字符”所以您可能无论如何都想将其切换为更好的“仅数字编辑”组件...

标签: delphi edit number-formatting


【解决方案1】:

我不知道更改该消息值的直接方法(由 Windows 处理),但您可以显示自己的消息,然后避免显示原始 Windows 提示气球,使用 Abort 过程OnKeyPress 事件。

检查此示例

procedure TForm1.Edit1KeyPress(Sender: TObject; var Key: Char);
begin
  if not (CharInSet(Key,['0'..'9',#8,#9]))  then      
  begin
    ShowHintMessage('Only numbers please');//you must write this function 
    Abort;//this will prevent which the original windows hint was shown
  end;
end;

您必须知道该代码将阻止对控件执行剪贴板操作。

更新

我更新代码以允许使用 Tab(#9) 和 Back space(#8) 字符。

【讨论】:

  • CTRL+V 会很轻松地解决这个问题。
  • @David,也许你误解了我的回答,代码是与NumbersOnly 属性一起使用的。不能单独验证整数。
  • 当然粘贴会绕过此代码并以 Windows 默认结束
  • @Arash - # 引入的数字是 Delphi 字符,由来自 ASCII table 的十进制值表示。所以#13 表示 Enter key#27#127 是 Escape 和 Delete 。如果您从集合中删除- key,则按下它时将不会收到 error 消息。
  • @Arash - 因为负值;)如果你不想要它们,只需省略'-'
【解决方案2】:

查看 VCL 源代码,看起来该消息是由 windows 生成的,而不是由 Delphi 生成的。也就是说,VCL 只是包装了存在于 windows 中的功能。因此,修改消息似乎并不容易。

【讨论】: