简体   繁体   中英

Double click event on object created at run time - Delphi

I have created a simple Delphi form with a button that, when pressed, creates a label object in run time. I have created an on double click event for the label that shows a message to the screen. The problem is that after creating the label, I have to double click on the form before the double click event works on the label. Obviously this is not ideal as I would like to be able to double click on the label and trigger the event without having to first double click the form.

Here is the code for my form:

unit Unit4;

interface

uses
  Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
  Dialogs, StdCtrls;

type
  TForm4 = class(TForm)
    Button1: TButton;
    procedure Button1Click(Sender: TObject);
    procedure FormDblClick(Sender: TObject);
    procedure MyLabelDblClick(Sender:TObject);
  private
    { Private declarations }
    LabelObject: TLabel;
  public
    { Public declarations }
  end;

var
  Form4: TForm4;

implementation

{$R *.dfm}

procedure TForm4.Button1Click(Sender: TObject);
begin
  LabelObject := TLabel.Create(Self);
  LabelObject.Left := 100;
  LabelObject.Top := 100;
  LabelObject.Width := 200;
  LabelObject.Height := 20;
  LabelObject.Visible := True;
  LabelObject.Parent := Self;
  LabelObject.Caption := 'My Run Time Label';
  LabelObject.Cursor := crHandPoint;
end;

procedure TForm4.FormDblClick(Sender: TObject);
begin
  LabelObject.OnDblClick := MyLabelDblClick;
end;

procedure TForm4.MyLabelDblClick(Sender: TObject);
begin
  showmessage('You double clicked My Run Time Label');
end;

end.

Thanks in advance for any help with this matter.

The problem is that after creating the label, I have to double click on the form before the double click event works on the label.

Assign LabelObject.OnDblClick when creating the label, ie inside the Button1Click event.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM