Link to home
Start Free TrialLog in
Avatar of deha2228
deha2228

asked on

onKeypress Event

I would like to have a editbox in which we can only type numbers and the backspace. I think I have to use the onKeypress event and limit the access to ascii codes but the onkeypress event returns a char.  

Thanks
Avatar of JimBob091197
JimBob091197

What about trapping the WM_CHAR message?

E.g.
In your component's declaration:
procedure WMChar(var Msg: TMessage); message WM_CHAR;

In your code:
procedure TMyEdit.WMChar(var Msg: TMessage);
begin
  // Only allow backspace, ENTER, Escape and 0..9
  if (TWMKey(Msg).CharCode in [8, 13, 27, 48..57]) then
    inherited;
end;

Cheers,
JB
ASKER CERTIFIED SOLUTION
Avatar of Thaddy
Thaddy

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Hello all!

I dont like TMaskEdit. It's kinda crappy. I rahter create my own EditBox as deha2228 is going to do. JimBob's solution is prefect for that task and is very easy to implement ;-)

Gotta get back to class ;->

Regards,
Viktor Ivanov
Avatar of kretzschmar
hi deho2228,

help this codesample

procedure TForm1.Edit1KeyPress(Sender: TObject; var Key: Char);
const validchars = [#8,'0','1','2','3','4','5','6','7','8','9'];
begin
  if not(key in validchars) then key := #0
end;

meikl
Here is an easier way...

procedure TForm1.Edit1KeyPress(Sender: TObject; var Key: Char);
begin
  if not key in [#8, #13, #27 '.', '0'..'9'] then key := #0;
end;

Regards,
Viktor Ivanov
hi viktor,

your comment is just the same, but i ask you for what do you use enter and Escapekey in an editfield?

well my const line could like shown as follows

      const validchars = [#8,'0'..'9'];

and the point if want to use can be added

meikl
My point is that you could use the shorter way instead of writing all the chars like so...
const validchars = [#8,'0','1','2','3','4','5','6','7','8','9'];

I added some other characters indeed