2010년 11월 13일 토요일

A CListBox with automatic HSCROLL maintenance

http://www.flounder.com/hscroll.htm

A CListBox with automatic HSCROLL maintenance

Overview

A question that seems to come up about once a week in the newsgroup goes something like "I checked the horizontal scroll style in my ListBox, and I don't see any scrollbar. What can I do?"
Horizontal scrolling is poorly understood and even more poorly documented. In order for horizontal scrolling to work, you have to call the SetHorizontalExtent method and set the total width of the horizontal space being used by the entries in the ListBox. If the horizontal extent is larger than the client area of the listbox, the horizontal scrollbar will appear, providing you have selected the horizontal scroll style. You need both to be set to get the effect.
Unfortunately, this is hard to do in the parent window. It involves having to do the computation at every site where you add a string. This is not well object-oriented. So what I've done is create a new class derived from CListBox that incorporates this functionality automatically.
The way I do this is maintain a value which is the maximum width set thus far. Whenever a new string is added, I update the width. When strings are deleted I update the width. I do this by overriding the ResetContent, InsertItem, AddItem, and DeleteString methods.
Note that this works only for non-owner-drawn list boxes. For owner-drawn, it is somewhat easier because you can maintain it in the DrawItem handler.
You can download the sample code, but here's some excerpts. The sample code includes a complete project which demonstrates the scrolling.
Note that to include this class in your project, you need to include the source file in your project, then delete the .clw file and re-invoke the ClassWizard to get it to see the new class (Microsoft used to allow the importation of classes directly, but this feature seems to have been deleted in the latest versions of Visual Studio). You can then create control variables using the CHListBox class directly in ClassWizard. If you don't do the rebuild of the .clw file, you will have to hand-edit your header file. If you don't know how to do this, check out my essay on Avoiding GetDlgItem.

댓글 없음:

댓글 쓰기