CyprUS
CyprUS

Reputation: 4239

how to disable certain keys in delphi

I have added the following code to my program which, as i understood, must disable alphabets from being entered. I set the form's KeyPreview property to True, Next i added this code

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

which was defined as

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

This does not seem to work, as i am able to enter a-z in the form's edit components; what am i doing wrong?

This is the code for my program

 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.

Upvotes: 2

Views: 10723

Answers (4)

CyprUS
CyprUS

Reputation: 4239

Problem solved. Setting the OnKeyPress event in the event tab worked.

Use the Object Inspector of the Form to set the OnkeyPress event. I had written the code but not assigned the event through the Object Inspector. Hence , the event was not registered and it was not firing.

Upvotes: 3

Cosmin Prund
Cosmin Prund

Reputation: 25678

You didn't mention Delphi version. If you're on a pre-Unicode version, simply make sure you handle both lowercase and uppercase char like this:

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

If you're on Unicode delphi, include the Character unit and try this:

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

Or you can try to use IsCharAlpha API function:

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

Upvotes: 2

Wim ten Brink
Wim ten Brink

Reputation: 26682

While reading between the lines, it seems as if you want to allow upper-case letters, but not lowercase. Instead of filtering the lowercase characters, why not set the CharCase property of the editbox to ecUpperCase? That way, all characters entered are converted to uppercase.

Upvotes: 0

David Heffernan
David Heffernan

Reputation: 612884

Your code works fine in that it blocks 'a' to 'z'. Perhaps your problem is that it doesn't block upper case characters. For that you would need:

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

Upvotes: 3

Related Questions