所以我已经有了代码.但是当它运行时它不允许退格键,我需要它来允许退格键并删除空格键,因为我不想要空格.
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;
Run Code Online (Sandbox Code Playgroud)
需要帮助谢谢:D
请注意代码中已有的注释:
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;
Run Code Online (Sandbox Code Playgroud)
最好将允许键作为常量放入集合中(速度、优化):
更新#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;
Run Code Online (Sandbox Code Playgroud)
为了获得更好的结果,请查看 DevExpress、JVCL、EhLib、RxLib 和许多其他库中包含的 TNumericEdit 组件。