Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to free control inside its event handler?

Tags:

delphi

Does anybody know the trick, how to free control inside its event handler ? According delphi help it is not possible...

I want to free dynamicaly created TEdit, when Self.Text=''.

TAmountEdit = class (TEdit)
.
.
public
  procedure KeyUp(var Key: Word; Shift :TShiftState);
end;

procedure TAmountEdit.KeyUp(var Key: Word; Shift :TShiftState);
begin
inherited;
if Text='' then Free; // after calling free, an exception arises
end;

How should do to achieve the same effect?

Thanx

like image 638
lyborko Avatar asked Mar 23 '10 18:03

lyborko


2 Answers

The solution is to post a queued message to the control, which it responds to by destroying itself. Ny convention we use CM_RELEASE which is the private message used by TForm in its implementation of the Release method that performs an analogous task.

interface

type
  TAmountEdit = class (TEdit)
    ...
    procedure KeyUp(var Key: Word; Shift :TShiftState); override;
    procedure HandleRelease(var Msg: TMessage); message CM_RELEASE;
    ...
  end;

implementation

procedure TAmountEdit.KeyUp(var Key: Word; Shift :TShiftState);
begin
  inherited;
  if Text = '' then
    PostMessage(Handle, CM_RELEASE, 0, 0);
end;

procedure TAmountEdit.HandleRelease(var Msg: TMessage);
begin
  Free;
end;

The control is destroyed when the application next pumps its message queue.

like image 87
kroimon Avatar answered Nov 16 '22 03:11

kroimon


Before implementing this I would stop and ask "Is this really the best approach?"

Do you really want an edit control class that always destroys itself when key input results in the Text property becoming an empty string?

Is it not more likely to be the case that you have a specific form/dialog where this behaviour is required? In which case, there is no problem... you can free the edit control in the KeyUp event handled by the form without incurring an Access Violation.

like image 39
Deltics Avatar answered Nov 16 '22 01:11

Deltics