Reputation: 93
I'm making a little project in Delphi 7, and there are 2 listboxes on form presented. Now I need to synchronize scrollbars of these Listboxes. Listboxes are guaranteed to have same number of items. Synchronization should be made when User moves one of scrollbars. I guess it should be something with 'Perform' method, but I'm new to it.
Upvotes: 3
Views: 2823
Reputation: 6587
To set the top line of a list box you use TopIndex
.
You can create a TListbox
descendent that handles the WM_VSCROLL
(and WM_HSCROLL
if you want). You can then hook into this and update the second list box. Here is an example of this. I am only doing the hook one way so scrolling listbox2 won't scroll listbox1.
You will need to add this TListBox override to your unit before the form declaration:
TListBox = class(Vcl.StdCtrls.TListBox)
private
FOnScroll: TNotifyEvent;
protected
procedure ListBoxScroll(var Message: TMessage); message WM_VSCROLL;
public
property OnScroll: TNotifyEvent read FOnScroll write FOnScroll;
end;
This adds a OnScroll event to the listbox. The implementation for this class:
procedure TListBox.ListBoxScroll(var Message: TMessage);
begin
inherited;
if Assigned(FOnScroll) then
FOnScroll(Self);
end;
You can then hook up the event in code:
procedure TMyForm.FormCreate(Sender: TObject);
begin
listbox1.OnScroll := DoScrollListBox1;
end;
The code for DoScrollListBox1 is very simple:
procedure TMyForm.DoScrollListBox1(Sender: TObject);
begin
listbox2.TopIndex := listbox1.TopIndex;
end;
This handles the scrolling by using the scroll bar. You will also need to add the following line to your OnClick of the listbox so keyboard actions will also trigger the scrolling.
procedure TMyForm.ListBox1Click(Sender: TObject);
begin
...
listbox2.TopIndex := listbox1.TopIndex;
...
end;
Upvotes: 5