It seems that .Net library doesn’t provide any way to scroll contents of ListBox through code. Selecting an item by setting SelectedIndex automatically scrolls the list to bring the item into view but this may not produce the desired effect. In my case, I wanted to programmatically select an item and make it the first visible item in the list. This effect cannot be achieved through changing SelectedIndex.
The way around this problem is to invoke Windows API SendMessage function.
To call a function from an un-managed DLL, we have to declare it along with DLLImport attribute.
As the declaration shows, we have supply four arguments.
This is the handle to ListBox Control. We can get the handle through Handle property of ListBox control e.g. myListBox.Handle
This should be set as WM_VSCROLL. It says that we want to send message for scrolling vertically. Find list of messages that could be passed to a control here.
This 32 bit parameter has two parts.
Lower 16 bits called LOWORD should specify one of the scroll bar commands. In our case, it should be SB_THUMBPOSITION.
Higher 16 bits called HIWORD should specify the numerical value for position of the scroll bar thumb. If we pass the index of a list item, list will scroll such that the item becomes the first visible item in the list.
This parameter is for additional message specific information. For our purposes, we will just pass 0.
Following is the SendMessage function call to scroll the list. First, we define the constants WM_VSCROLL and SB_THUMBPOSITION. Then we develop the thrid paramter by combining LOWORD and HIWORD. Finally the function is called.