Search code examples
delphinumbersprocedure

Procedure to show a hint when user press a key that is not a number in TEdit


I want to write a function to a TEdit that have the property NumbersOnly active. If the user, instead of entering a number, entered a letter, the function would show a custom message using ShowHint with the key entered.

I wrote this code below. But the problem is that whatever key that I press, numbers or letters, the hint appears. To see the problem of where need help, this is the code:

procedure nHint(hHint: string; AEdit: TEdit);
var
point: TPoint;
Key: Char;
begin
if AEdit.NumbersOnly = true then
begin
if not(CharInSet(Key, ['0' .. '9', #8])) then
begin
  form1.BalloonHint1.Description := hHint;
  point.X := AEdit.Width div 2;
  point.Y := AEdit.Height div 1;
  form1.BalloonHint1.ShowHint(AEdit.ClientToScreen(point));
  Abort;
end
else
begin
  form1.BalloonHint1.HideHint;
end;
end;
end;

procedure TFrame1.Edit1KeyPress(Sender: TObject; var Key: Char);
begin
 nHint('Number Only', Edit1);
end;

Solution

  • Your problem is that you decalre key as a local variable, which you do not initialize.

    In order for making you procedure work you need to pass key as a parameter to you procedure:

    Change

      procedure nHint(hHint: string; AEdit: TEdit);
    

    To this:

    procedure nHint(hHint: string; AEdit: TEdit; var Key: Char);
    

    And remove the local variable key

    When you call it, you pass the extra parameter.

    So change this :

    nHint('Number Only', Edit1);
    

    to this:

      nHint('Number Only', Edit1, Key);
    

    then it works