delphi – 如何将事件作为函数参数传递?

前端之家收集整理的这篇文章主要介绍了delphi – 如何将事件作为函数参数传递?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我有一个表单,其中包含我创建的有用过程列表,我经常在每个项目中使用.我正在添加一个过程,可以很容易地将可点击图像添加到TListBoxItem的TAccessory上.该过程目前正在进入ListBox,但我还需要它来为图像调用OnClick事件的过程.这是我现有的代码
function ListBoxAddClick(ListBox:TListBox{assuming I need to add another parameter here!! but what????}):TListBox;
var
  i       : Integer;
  Box     : TListBox;
  BoxItem : TListBoxItem;
  Click   : TImage;
begin
  i := 0;
  Box := ListBox;
  while i <> Box.Items.Count do begin
    BoxItem := Box.ListItems[0];
    BoxItem.Selectable := False;

    Click := Timage.Create(nil);
    Click.Parent := BoxItem;
    Click.Height := BoxItem.Height;
    Click.Width := 50;
    Click.Align  := TAlignLayout.alRight;
    Click.TouchTargetExpansion.Left := -5;
    Click.TouchTargetExpansion.Bottom := -5;
    Click.TouchTargetExpansion.Right := -5;
    Click.TouchTargetExpansion.Top := -5;
    Click.OnClick := // this is where I need help

    i := +1;
  end;
  Result := Box;
end;

将以调用函数的形式定义所需的过程.

解决方法

由于 OnClick事件的类型为 TNotifyEvent,因此您应该定义该类型的参数.看看这个(我希望自我解释)的例子:
type
  TForm1 = class(TForm)
    Button1: TButton;
    ListBox1: TListBox;
    procedure Button1Click(Sender: TObject);
  private
    procedure TheClickEvent(Sender: TObject);
  end;

implementation

procedure ListBoxAddClick(ListBox: TListBox; OnClickMethod: TNotifyEvent);
var
  Image: TImage;
begin
  Image := TImage.Create(nil);
  // here is assigned the passed event method to the OnClick event
  Image.OnClick := OnClickMethod;
end;

procedure TForm1.Button1Click(Sender: TObject);
begin
  // here the TheClickEvent event method is passed
  ListBoxAddClick(ListBox1,TheClickEvent);
end;

procedure TForm1.TheClickEvent(Sender: TObject);
begin
  // do something here
end;

猜你在找的Delphi相关文章