Search code examples
delphidelphi-7delphi-2010delphi-2009

Synchronize 5 ListBoxes together


im working on a little Project right now and i want to synchronize 5 listBoxes scrolling together. The names of the listboxes are:

KidList
PointList
NoteList
CommentList
CommentListKid

How can i do it?


Solution

  • You could try the following technique.

    First, add a private field

      private
        SyncBoxes: TArray<TListBox>;
    

    to your form and initialise it when the form is created:

    procedure TForm1.FormCreate(Sender: TObject);
    begin
      SyncBoxes := [ListBox1, ListBox2, ListBox3, ListBox4];
    end;
    

    Then define the following interposer class:

    type
      TListBox = class(Vcl.StdCtrls.TListBox)
      strict private
        procedure Sync;
      protected
        procedure WMVScroll(var Message: TWMVScroll); message WM_VSCROLL;
        procedure CNCommand(var Message: TWMCommand); message CN_COMMAND;
        procedure WMMouseWheel(var Message: TWMMouseWheel); message WM_MOUSEWHEEL;
      end;
    

    implemented as

    procedure TListBox.CNCommand(var Message: TWMCommand);
    begin
      inherited;
      if Message.NotifyCode = LBN_SELCHANGE then
        Sync;
    end;
    
    procedure TListBox.Sync;
    var
      LB: TListBox;
    begin
      for LB in Form1.SyncBoxes do
        if LB <> Self then
          LB.TopIndex := Self.TopIndex;
    end;
    
    procedure TListBox.WMMouseWheel(var Message: TWMMouseWheel);
    begin
      inherited;
      Sync;
    end;
    
    procedure TListBox.WMVScroll(var Message: TWMVScroll);
    begin
      inherited;
      Sync;
    end;
    

    Of course, in a real app you would refactor this.

    The result is possibly good enough:

    Video of four synchronised list boxes being scrolled.

    The list box's scrolling animation makes synchronisation a little bit delayed, however.