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

前端之家收集整理的这篇文章主要介绍了delphi – 如何将事件作为函数参数传递?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我有一个表单,其中包含我创建的有用过程列表,我经常在每个项目中使用.我正在添加一个过程,可以很容易地将可点击图像添加到TListBoxItem的TAccessory上.该过程目前正在进入ListBox,但我还需要它来为图像调用OnClick事件的过程.这是我现有的代码
  1. function ListBoxAddClick(ListBox:TListBox{assuming I need to add another parameter here!! but what????}):TListBox;
  2. var
  3. i : Integer;
  4. Box : TListBox;
  5. BoxItem : TListBoxItem;
  6. Click : TImage;
  7. begin
  8. i := 0;
  9. Box := ListBox;
  10. while i <> Box.Items.Count do begin
  11. BoxItem := Box.ListItems[0];
  12. BoxItem.Selectable := False;
  13.  
  14. Click := Timage.Create(nil);
  15. Click.Parent := BoxItem;
  16. Click.Height := BoxItem.Height;
  17. Click.Width := 50;
  18. Click.Align := TAlignLayout.alRight;
  19. Click.TouchTargetExpansion.Left := -5;
  20. Click.TouchTargetExpansion.Bottom := -5;
  21. Click.TouchTargetExpansion.Right := -5;
  22. Click.TouchTargetExpansion.Top := -5;
  23. Click.OnClick := // this is where I need help
  24.  
  25. i := +1;
  26. end;
  27. Result := Box;
  28. end;

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

解决方法

由于 OnClick事件的类型为 TNotifyEvent,因此您应该定义该类型的参数.看看这个(我希望自我解释)的例子:
  1. type
  2. TForm1 = class(TForm)
  3. Button1: TButton;
  4. ListBox1: TListBox;
  5. procedure Button1Click(Sender: TObject);
  6. private
  7. procedure TheClickEvent(Sender: TObject);
  8. end;
  9.  
  10. implementation
  11.  
  12. procedure ListBoxAddClick(ListBox: TListBox; OnClickMethod: TNotifyEvent);
  13. var
  14. Image: TImage;
  15. begin
  16. Image := TImage.Create(nil);
  17. // here is assigned the passed event method to the OnClick event
  18. Image.OnClick := OnClickMethod;
  19. end;
  20.  
  21. procedure TForm1.Button1Click(Sender: TObject);
  22. begin
  23. // here the TheClickEvent event method is passed
  24. ListBoxAddClick(ListBox1,TheClickEvent);
  25. end;
  26.  
  27. procedure TForm1.TheClickEvent(Sender: TObject);
  28. begin
  29. // do something here
  30. end;

猜你在找的Delphi相关文章