Microsoft KB Archive/192184

= How To Add a Horizontal Scroll Bar to a Visual Basic ListBox =

Article ID: 192184

Article Last Modified on 7/15/2004

-

APPLIES TO


 * Microsoft Visual Basic 5.0 Learning Edition
 * Microsoft Visual Basic 6.0 Learning Edition
 * Microsoft Visual Basic 5.0 Professional Edition
 * Microsoft Visual Basic 6.0 Professional Edition
 * Microsoft Visual Basic 5.0 Enterprise Edition
 * Microsoft Visual Basic 6.0 Enterprise Edition

-



This article was previously published under Q192184



SUMMARY
The normal ListBox that comes with Visual Basic for Windows does not have a horizontal scroll bar. This can be a problem when the item in a ListBox extends past the boundaries of the ListBox. To add a horizontal scroll bar to the control, you can call the Windows API SendMessage function with the LB_SETHORIZONTALEXTENT constant.



MORE INFORMATION
This message sets the width in pixels by which a ListBox can scroll horizontally. If the width of the ListBox is smaller than this value, a horizontal scroll bar will be added to allow horizontally scrolling items in the ListBox.

Step-by-Step Example
 Create a new Standard EXE project in Visual Basic. Form1 is created by default. Add a CommandButton and a ListBox to Form1.  Paste the following code into the general declaration section of Form1: Option Explicit

Private Declare Function SendMessageByNum Lib "user32" _ Alias "SendMessageA" (ByVal hwnd As Long, ByVal _       wMsg As Long, ByVal wParam As Long, ByVal lParam As Long) As Long Const LB_SETHORIZONTALEXTENT = &H194

Private Sub Command1_Click Dim s As String Static x As Long s = InputBox("Please enter any text", "List scroll", _          "this is a simple scrollbar sample for demonstration purposes") List1.AddItem s        If x < TextWidth(s & "  ") Then x = TextWidth(s & " ") If ScaleMode = vbTwips Then _ x = x / Screen.TwipsPerPixelX ' if twips change to pixels SendMessageByNum List1.hwnd, LB_SETHORIZONTALEXTENT, x, 0 End If     End Sub

 Run the project and click on Command1. You will be prompted to enter a text string to be added to the ListBox. Each time you enter a string, the code checks to see if it is longer than the previous longest string and will adjust the scroll bar as necessary.

