views:

993

answers:

2

Hello,

I have this code

procedure TForm1.Edit1KeyDown(Sender: TObject; var Key: Word; Shift: TShiftState);
var
begin
  if not (Key in [Ord('0')..Ord('9')]) then
    Key := 0;
end;

and it worked fine with Delphi 2007. When I upgraded to Delphi 2009 and I try to press any letter it is accepted and the Key := 0 does not trap the input?

Anyone encountered the same behavior?

+13  A: 

Are you sure that this worked in Delphi 2007? I just tried the code in Delphi 2007 and 2009. And both behave the same (No key stroke is eaten) If you want to accept only digits you should use the OnKeyPress event and set the Key parameter to #0.

Andreas Hausladen
It should have worked in Delphi 2006 at least. I am sure it worked when build with Delphi 2007 R2.
Gad D Lord
Delphi 5, 6, 7, 2005, 2006, 2007 and 2009 behave all the same. I do not have installed Delphi 1, 2, 3 and 4, so I can't confirm it for those.
Andreas Hausladen
+1 on the tip to use OnKeyPress, also because '0'..'9' on the numeric keypad produce different key codes than the standard number keys. The code snippet in the question wouldn't work for the numeric keypad, anyway.
mghie
+1 on trying it on 7 versions and make an apology because you haven't used 4 earlier versions.
Gamecat
+1 on what Gamecat said. Nice comment, Andreas!
Ken White
I installed Delphi 2007 and tried it myself. You are all right. I recoded the logic in OnKeyPress and works fine for now.
Gad D Lord
+3  A: 

OnKeyDown gives you a scancode. OnKeyPress gives you the character. Been that way in every version of Delphi I can remember.

Jim McKeeth