delphi - 如何使用此 CustomSort 函数对 ListView 进行排序?

标签 delphi callback

如果 customsort 函数与变量一起传入,似乎会发生访问冲突。


public 
...
col: integer;
...

Procedure listviewcol;
begin
  col:=5
...
end;

procedure TForm1.sortcol(listview: tlistview);
  function CustomSortProc(Item1,Item2: TListItem;
    OptionalParam: integer): integer;stdcall;
  begin
    Result := AnsiCompareText(Item2.subitems.Strings[col], Item1.subitems.Strings[col]);
  end;
begin
  ListView.CustomSort(@CustomSortProc,0);
end;

这会提示错误。//访问冲突

但是如果我们将 AnsicompareText 中的 col 更改为 5,则效果很好。

procedure TForm1.sortcol(listview: tlistview);
  function CustomSortProc(Item1,Item2: TListItem;
    OptionalParam: integer): integer;stdcall;
  begin
    Result := AnsiCompareText(Item2.subitems.Strings[5], Item1.subitems.Strings[5]);// it works.
  end;
begin
  ListView.CustomSort(@CustomSortProc,0);
end;

如何修复它。 请帮忙。非常感谢。

最佳答案

您不能在回调函数中访问 col,它不是您表单的方法。您在方法中嵌套回调的技巧是徒劳的。 ;) 如果您需要访问表单字段,请使用 OptionalParam 以便能够在回调中引用您的表单。

begin
  ListView.CustomSort(@CustomSortProc, Integer(Self));
  [...]

function CustomSortProc(Item1,Item2: TListItem;
  OptionalParam: integer): integer; stdcall;
var
  Form: TForm1;
begin
  Form := TForm1(OptionalParam);
  Result := AnsiCompareText(Item2.subitems.Strings[Form.col],
      Item1.subitems.Strings[Form.col]);

当然,如果这是您唯一需要的,您可以在“OptionalParam”中发送 col 的值。或者,您可以将“col”设为全局变量而不是字段,或者使用“Form1”全局变量本身,如果未注释掉,IDE 会将其放在实现部分之前。

您还可以使用 OnCompare事件。

关于delphi - 如何使用此 CustomSort 函数对 ListView 进行排序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4096081/

相关文章:

delphi - 如何在运行时访问 Delphi 2009 功能区按钮的选中属性?

delphi - 如何安装 OmniXml for Delphi Xe2/OExport XLSX/ODS native Delphi/Lazarus 导入/导出库

c++ - 共享指针和回调注册的结构。当出于我以外的原因调用回调时,原始指针值发生了变化

callback - 使用 plotly express 并在一页上有多个图形时,随机出现导入错误

jquery - ajax 成功后循环 JSON 响应

delphi - 如何取消最后一条AT命令(Delphi - TComport)?

delphi - 如何在 Delphi 中使用 TMediaPlayer 从麦克风输入录制音频?

delphi - ClientDataSet 上的 StatusFilter

javascript - Node.js - Javascript - 如何将变量传递给回调函数

javascript - 处理 Angular 1.5 组件中的回调函数