简体   繁体   English

TEdit、Delphi 中唯一的数字

[英]Only number in TEdit, Delphi

How can I add a TEdit that only accept numbers?如何添加仅接受数字的TEdit I search information but nothing helps me.我搜索信息,但没有任何帮助。

I need a TEdit that does not accept any letter or strings.我需要一个不接受任何字母或字符串的TEdit

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

In modern Delphi versions (D2009+) you can use the TEdit.NumbersOnly property.在现代 Delphi 版本 (D2009+) 中,您可以使用TEdit.NumbersOnly属性。

Allows only numbers to be typed into the text edit.只允许在文本编辑中输入数字。 Use NumbersOnly to prohibit entry of non-numeric characters in the textfield.使用 NumbersOnly 禁止在文本字段中输入非数字字符。 Note, however, that a user can paste non-numeric characters in the textfield even when this property is set.但是请注意,即使设置了此属性,用户也可以在文本字段中粘贴非数字字符。

Another option is to use the TMaskEdit component.另一种选择是使用TMaskEdit组件。 An EditMask property using following characters can produce a valid numeric input, including negative values.使用以下字符的EditMask属性可以生成有效的数字输入,包括负值。

# : Accepts an optional sign or numeric digit
0 : Accepts a numeric character
9 : Accepts an optional numeric character

For older Delphi versions, ie 2006, (after @MBo hint), the code can be like this (can be put to Form.OnCreate):对于旧的 Delphi 版本,即 2006,(在@MBo 提示之后),代码可以是这样的(可以放到 Form.OnCreate 中):

CurrentStyle := GetWindowLong(Edit1.Handle, GWL_STYLE);
CurrentStyle := CurrentStyle or ES_NUMBER;
SetWindowLong(Edit1.Handle, GWL_STYLE, CurrentStyle);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM