Adding a horizontal scrollbar to CListBox in windows

Description of Listbox:
Provides the functionality of a Windows list box.
class CListBox : public CWnd
A list box displays a list of items, such as filenames, that the user can view and select.
In a single-selection list box, the user can select only one item. In a multiple-selection list box, a range of items can be selected. When the user selects an item, it is highlighted and the list box sends a notification message to the parent window.
You can create a list box either from a dialog template or directly in your code. To create it directly, construct the CListBox object, then call the Create member function to create the Windows list-box control and attach it to the CListBox object. To use a list box in a dialog template, declare a list-box variable in your dialog box class, then use DDX_Control in your dialog box class’s DoDataExchange function to connect the member variable to the control. (this is done for you automatically when you add a control variable to your dialog box class.)
Its possible to go to the resource file and add your settings directly. See below:
But sometimes, this wont do the work. Even though you get the vertical scrollbar automatically, somehow the horizontal scrollbar refuses to show up. We need to use TEXTMETRIC and CDC to do that. We read the length of the input and adjust the width according to that:
TEXTMETRIC vartm; //contains information about the font
The CDC object provides member functions for working with a device context, such as a display or printer, as well as members for working with a display context associated with the client area of a window.
Do all drawing through the member functions of a CDC object. The class provides member functions for device-context operations, working with drawing tools, type-safe graphics device interface (GDI) object selection, and working with colors and palettes. It also provides member functions for getting and setting drawing attributes, mapping, working with the viewport, working with the window extent, converting coordinates, working with regions, clipping, drawing lines, and drawing simple shapes, ellipses, and polygons. Member functions are also provided for drawing text, working with fonts, using printer escapes, scrolling, and playing metafiles.
//varListbox is the variable name of CListBox
//you would need to call this inside the InitDialog of listbox, so that these changes are reflected in listbox

CDC* varDC = varListbox.GetDC();
if( varDC) //check for NULL
varDC ->GetTextMetrics(&varTM);
size_t sizeOfHz = varTM.tmAveCharWidth * 500; //you can replace 500 with any number you want
m_varListbox.SetHorizontalExtent(sizeOfHz );
//release CDC

Leave a Reply

Your email address will not be published. Required fields are marked *