如何在delphi中禁用某些键

时间:2011-06-27 07:52:55

标签: delphi delphi-7

我已将以下代码添加到我的程序中,据我所知,必须禁止输入字母。 我将表单的KeyPreview属性设置为True, 接下来我添加了这段代码

procedure FormKeyPress(Sender: TObject; var Key: Char) ;

被定义为

 procedure TFibo.FormKeyPress(Sender: TObject; var Key: Char);
  begin
 if Key in ['a'..'z'] then Key := #0
  end;

这似乎不起作用,因为我能够在表单的编辑组件中输入a-z;我做错了什么?

这是我的程序的代码

 unit Unit1;

 interface

 uses
   Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
   Dialogs, StdCtrls;

 type
   TFibo = class(TForm)
   lblInput: TLabel;
   edtInput: TEdit;
   procedure FormKeyPress(Sender: TObject; var Key: Char) ;
 end;

var
  Fibo: TFibo;

implementation

{$R *.dfm}

procedure Tfibo.FormKeyPress(Sender:TObject;var Key:char);
begin
  if Key in ['a'..'z', 'A'..'Z'] then
    Key := #0
end;

end.

4 个答案:

答案 0 :(得分:3)

你的代码工作正常,因为它阻止'a'到'z'。也许你的问题是它不会阻止大写字符。为此你需要:

if Key in ['a'..'z', 'A'..'Z'] then
  Key := #0

答案 1 :(得分:3)

问题解决了。在事件选项卡中设置OnKeyPress事件有效。

使用Form的Object Inspector设置OnkeyPress事件。我编写了代码但没有通过Object Inspector分配事件。因此,事件没有登记,也没有解雇。

答案 2 :(得分:2)

你没有提到Delphi版本。如果您使用的是Unicode前版本,只需确保同时处理小写和大写字符:

if Key in ['a'..'z', 'A'..'Z'] then Key := #0;

如果您使用的是Unicode delphi,请添加Character单元并尝试此操作:

if TCharacter.IsLetter(Key) then Key := #0;

或者您可以尝试使用IsCharAlpha API函数:

if IsCharAlpha(Key) then Key := #0;

答案 3 :(得分:0)

在读取行之间时,似乎您想要允许使用大写字母,而不是小写字母。为什么不将编辑框的CharCase属性设置为ecUpperCase,而不是过滤小写字符?这样,输入的所有字符都将转换为大写。

相关问题