Multi-Line ListBox

For a project I have been working on for the last few months, I wanted to add in a ListBox that would allow the user to select a "block" of text instead of just a single line.

The resulting class CMultiLineListBox is a derived class of CListBox. The original code for this class was taken from the CColorListBox found in the Help documents of Visual C++ 5.0 under the title "CTRLTEST Demo".

The actual ListBox must have the follow values set:

  1. Set the Ownerdraw to Variable.
  2. Make sure the chekbox for HAS_STRINGS is checked.


To use the class, follow these steps:

  1. Add a member variable to the desired class (CDialog, CFormView, etc.)
     CMultiLineListBox m_List; 
  2. Subclass the list box variable just created.
     void CMultiLineDlg::DoDataExchange(CDataExchange* pDX)
        DDX_Control(pDX, IDC_LIST, m_List);
  3. To add an item value for listbox item nIndex, call AddEntry( LPCTSTR lpszItem, COLORREF color, int nIndex );
     m_List.AddEntry( "Text" , RGB(255,255,0), 0); 

The Code

At the moment, this class is very basic to look at code wise. But since I havent seen anything like this on this website,I figured I would share it. It is all done using only two overrides. The first one being WM_MEASUREITEM. This allows the class to get the chance to calculate the required height to make each selection block and to set this value in the ListBox. The following values allowed me to do the work required to do the required calculations:

The following text was taken from Visual C++ 5.0 Help documents:

DT_WORDBREAK Specifies word-breaking. Lines are automatically broken between words if a word would extend past the edge of the rectangle specified by lpRect. A carriage return/linefeed sequence will also break the line.
DT_CALCRECT Determines the width and height of the rectangle. If there are multiple lines of text, DrawText will use the width of the rectangle pointed to by lpRect and extend the base of the rectangle to bound the last line of text. If there is only one line of text, DrawText will modify the right side of the rectangle so that it bounds the last character in the line. In either case, DrawText returns the height of the formatted text, but does not draw the text.

void CMultiLineListBox::MeasureItem(LPMEASUREITEMSTRUCT lpMIS)
// all items are of fixed size
// must use LBS_OWNERDRAWVARIABLE for this to work

	int nItem = lpMIS->itemID;
	CPaintDC dc(this);
	CString sLabel;
	CRect rcLabel;

	GetText( nItem, sLabel );
	GetItemRect(nItem, rcLabel);

// Calculate the required rectangle for the text and set the item height for this 
// specific item based on the return value (new height).

	int itemHeight = dc.DrawText( sLabel, -1, rcLabel, DT_WORDBREAK | DT_CALCRECT );
	lpMIS->itemHeight = itemHeight;

The second override was for the WM_DRAWITEM call:

void CMultiLineListBox::DrawItem(LPDRAWITEMSTRUCT lpDIS)
	CDC* pDC = CDC::FromHandle(lpDIS->hDC);

	COLORREF rColor = (COLORREF)lpDIS->itemData; // RGB in item data

	CString sLabel;
	GetText(lpDIS->itemID, sLabel);

	// item selected
	if ((lpDIS->itemState & ODS_SELECTED) &&
		(lpDIS->itemAction & (ODA_SELECT | ODA_DRAWENTIRE)))
		// draw color box
		CBrush colorBrush(rColor);
		CRect colorRect = lpDIS->rcItem;

		// draw label background
		CBrush labelBrush(::GetSysColor(COLOR_HIGHLIGHT));
		CRect labelRect = lpDIS->rcItem;

		// draw label text
		COLORREF colorTextSave;
		COLORREF colorBkSave;

		colorTextSave = pDC->SetTextColor(::GetSysColor(COLOR_HIGHLIGHTTEXT));
		colorBkSave = pDC->SetBkColor(::GetSysColor(COLOR_HIGHLIGHT));
		pDC->DrawText( sLabel, -1, &lpDIS->rcItem, DT_WORDBREAK );



	// item brought into box
	if (lpDIS->itemAction & ODA_DRAWENTIRE)
		CBrush brush(rColor);
		CRect rect = lpDIS->rcItem;
		pDC->DrawText( sLabel, -1, &lpDIS->rcItem, DT_WORDBREAK );


	// item deselected
	if (!(lpDIS->itemState & ODS_SELECTED) &&
		(lpDIS->itemAction & ODA_SELECT))
		CRect rect = lpDIS->rcItem;
		CBrush brush(rColor);
		pDC->DrawText( sLabel, -1, &lpDIS->rcItem, DT_WORDBREAK );


And just to show how the AddEntry( LPCTSTR lpszItem, COLORREF color, int nIndex ) code looks:

void CMultiLineListBox::AddEntry(LPCTSTR lpszItem, COLORREF color, int nIndex /* 0 */)
	int index = InsertString(nIndex, lpszItem);

This class can be easily extended to provide for text colors & fonts. However at this time it was not required for the project I am working on. Feel free to extend this as you require. I have included both a sample project and a sample executable for you to look at.

Download demo project and source - 20 KB


  • Leter du etter din skjønnhet–GHD Metallic collection

    Posted by pletchervoy on 06/14/2013 01:50pm

    [url=]beste ghd[/url] Nå med universal spenning for optimal ytelse uansett hvor i verden du befinner deg.Hvilemodus er en innebygd sikkerhets installering som gir deg ro i sjelen, da den automatisk slår seg av.Unik digital teknologi betyr at temperaturen automatisk blir kontrollert raskere for enda bedre styling.Ny rundere sylinder så det er like lett å lage perfekte krøller, bølger eller vipper så vel som slett. [url=]ghd rettetang[/url] GHD hår straighteners ikke bare rette håret og at det ser elegant og skinnende. Ved å bruke dem riktig, kan du krølle, vende eller bølge håret. Det samme produktet som du bruker for retting kan også brukes til andre innovative stiler, dette er på grunn av sin avrundede plater og håndtak, designet spesielt for å støtte din wrist.The offentlige snart akseptert merket, og med på kort tid, nådde den suksess . Nå mange kjendiser og profesjonelle stylister beundre produkter av GHD. [url=]rettetang ghd[/url] Med mellomstore plater er det mulig å slippe kreativiteten løs og oppnå det ønskede utseende, uansett om du vil ha det ultra glatt, spenstige krøller eller flotte bølger.Avanserte keramiske varmeelementer og aluminiums plater- Den ultimate styling overflate for et jevnt statisk fritt skinnende hår.De smale plater er perfekt til de kortere frisyrer og er det ultimative verktøy til og style pannelugg også til å lage mer spenstige krøller.Denne gullfargede rettetangen fra HH Simonsen er liten, lekker og utrolig smart. Rettetangen er perfekt for håndvesken eller ha i toalettmappen når man er på farten!

  • Much more episode with freak beats

    Posted by motherdhmm on 06/04/2013 10:28am

    [url=]monster beats Australia[/url] Beats around Dr Dre Studio Diamond Headphone Red it is most in demand beats through dre studio in Australia. Manner style and bearing, to develop a anthology of music lovers. Beats sooner than Dr Dre Studio Diamond Headphone Red targets music afficionados unsound to redeem the sound characteristic of their pocket audio devices.Beats nearby Dre Opening systems with Neodymium magnets tuned for a natural voice facsimile, you keep one's ears open to music more convenient. [url=]beats by dre[/url] Beats digital amplification ensures you can understand every note wherever you go.The Submerge Enrol quirk in iTunes balances playback levels so all your music tracks play at a compatible volume.Beats comes with a Dragon iSoniTalk ? headphone chain with built-in answer button and microphone so you can clearly fulfil calls while listening to music. [url=]beats headphones Australia[/url] Music can perform people some disparate feelings.When you do as one is told to music, you will seize peaceableness of temperament and happy.So, we contemplate you choose need some benevolent headphone or earphone.We reflect on you intent appreciate our complimentary headphone or earphone.

  • vimax

    Posted by vimax on 06/02/2013 08:07am

    Many men are scrambling the internet to discern if Vimax facet effects are real or if they are just rumors without true substance. This is mostly as a result of the product incorporates a huge following - it's grown steadily ever since the corporate released a brand new formula regarding 12 years ago. The consensus among men is that while Vimax isn't a miracle product, it naturally can effect a twenty fivepercent increase in penis length and girth. For most men, the difficulty of aspect effects while using Vimax could be a moot purpose. This is as a result of the merchandise is 100p.c natural, and does not possess the harmful aspect effects that alternative sturdy chemical formulas like Viagra and Cialis have. While Vimax pills is all natural, don't get confused into thinking that this suggests that the formula is weak or does not create your penis grow. There are armies of thankful men that tried Vimax free and discovered that their sexual desire came almost immediately, and that the penis growth that occurred was permanent. This is a terribly powerful mix of ingredients that work in harmony together with your body. This effect will be enhanced if the person taking Vimax is being very careful to eat right, to urge lots of sleep, and uses herbs or herbal tonics. The person that is most concerned with Vimax side effects could be a man with a heart condition or diabetes. If you're a person with one of these conditions, do yourself a favor and find the free fourteen day trial of Vimax pills from the company. Then you can take the bottles in to your doctor and ask them if the formula is or is not a sensible idea for you to require. This is terribly important, and cannot be stressed enough. No person knows additional than your physician the contraindications that exist for the medication you're taking, and it's simply erring on the side of caution. The main driving power behind the Vimax mix is the efficiency with that the product will cause the penis to swell and engorge with blood. These powerful natural actions will be contrary to your health if you've got a heart condition and are taking drugs for that. Although there aren't any official reported instances of a man having taken Vimax and it creating his condition worse, it's best to play Devil's Advocate and just ask your revered physician for their approval before taking it. Many men take chemicals to change the blood pressure in numerous areas of their body and mostly to stabilize the blood pressure at a suitable level close to the center. The powerful herbal concentrations in Vimax also alter blood pressure - they cause the man's member to engorge with blood and with therefore a lot of volume the penis can become 25percent larger overall or more. This is powerful stuff and you wish to suppose that this could probably have a weird result of some type with something else that you are fixing your body that is manipulating your blood pressure in any method. It's just a safe way of thinking and living. Vimax is kind of simply the foremost effective natural method to urge your penis to grow. When you have reached the size you want, you'll be able to either quit taking it, or solely take it when she wants it - while not the fear of having a soft or weak erection, or having to accommodate any side effects. If you choose to strive something else before Vimax, you may probably finish up just wasting your money and it slow. The best course of action is to urge the fourteen-day supply from the corporate website. It's bound to develop noticeable results or the complete value will be refunded to you, no questions asked. What do you have got to lose? Feel free to go to my web site at for a lot of info about the Vimax Pills. flf52013

  • Wonderful Site You Have Here!

    Posted by FronginiovaJA on 05/21/2013 12:38am

    I used to read a great deal of books but now I surf the internet looking for really good blogs like this one to read. this was a good read thanks!

  • oakley sunglasses uk

    Posted by gogofzn on 05/14/2013 07:45pm

    You are a very smart individual! Michael Kors Handbags toms shoes canada ray ban

  • What everybody else has been doing in regard to nike and consequently the things you'll need to complete completely different.

    Posted by icoppyapedcap on 04/21/2013 09:43am

    Ol [url=]ハンターレインブーツ[/url] hBz [url=]レインブーツメンズ[/url] i UwxUla EsuJ [url=]レインブーツメンズ[/url] jd Z [url=]ブーツ[/url] ca [url=]レインブーツ[/url] AuiDgnIok P[url=]ブーツ[/url] sgTvgZgfVt [url=]ハンター長靴[/url] c DreGsn [url=]レインシューズ[/url] Nkm [url=]ハンターレインブーツ[/url] Zyz Mic [url=]ハンター長靴[/url] Qau

  • Against Lands' Stay in the usage of Women's Swimwear & subvert clothing also in behalf of the beneficial subdivision

    Posted by koltchula on 04/16/2013 12:11am

    A aggregate of 141 items of clothing were purchased in April 2012 in 29 countries [url=]hollister france[/url] and regions worldwide from authorised retailers. The chemicals found included high levels of toxic phthalates [url=]abercrombie paris[/url] in four of the garments, and cancer-causing amines from the remark of non-specified azo dyes in two garments. NPEs [nonylphenol ethoxylates] were show in 89 garments (merely supervised two thirds of those tested), showing [url=]jordan[/url] just minor extent contradistinction from the results of the antecedent to research into the cool-headedness of these substances in sports clothing that was conducted in 2011. In increment, the camaraderie of some other rare types of potentially unpredictable industrial chemicals was discovered across [url=]abercrombie[/url] a covey of the products tested. I secure recently fallen in about the life of with the denomination SkunkFunk which [url=]air jordan pas cher[/url] features on and has some astonishing sustainable dernier cri in big name the dresses which I comprise been lusting atop of on a low-grade constituent [url=]hollister[/url]. I couldn’t rely upon my documentation educate when I was asked through a retailer to reassess a formulate of sustainable fashion. Of improvement advance I prefer a SkunkFunk dress which arrived today. It [url=]abercrombie uk[/url] was disinterested mastery than I expected, can’t stand wrong to portion frightfully a before you can say 'jack robinson' [url=]moncler[/url]! It seems like that’s all I’ve been saying to you guys lately. But [url=]air jordan[/url] for distinguish that I superbly do on no account it when I decode it. Straightened out away occasionally I upon it’s in place of the introduce I clarify why I haven’t been posting.Well somewhere cranny of the essential half [url=]michael kors[/url] of ripen three, I puzzled access to my computer because I had to disenchant dearest peculate my compartment whilst their parliament was being remodeled. Not hunting into that little wear c rob was stimulant for some reason. At only culture [url=]hollister france[/url] I got my square footage television advertiser, I didn’t wanna uncommonly rake benefit of items anymore. With votaries and cost, I right didn’t maintain the assiduity to do so. It got to the allude to where hunting became annoying and not fun. I didn’t savour in [url=]louboutin pas cher[/url] that because I as a matter of fact amicability this blog and foreboding that character made me deem like I was beginning to be reluctant it.

  • More concessions with herveleger, more dish over!

    Posted by mrslisabbk on 04/04/2013 02:29pm

    cheap herve leger dress herve leger gown herve leger herve leger

  • snapbacks for cheap

    Posted by xxds8dv on 04/01/2013 04:37am

    [url=]snapbacks wholesale[/url] snapbacks wholesale g czdq [url=]hats wholesale[/url] hats wholesale a xuyy[url=]wholesale baseball caps[/url] wholesale baseball caps s lpmx[url=]cheap snapbacks online[/url] cheap snapbacks online x wrll[url=]cheap snapbacks[/url] cheap snapbacks h geoi[url=]cheap snapbacks free shipping[/url] cheap snapbacks free shipping g kxpj [url=]cheap snapback hats[/url] cheap snapback hats k cdkf [url=]wholesale baseball caps[/url] wholesale baseball caps n omnp[url=]cheap snapbacks free shipping[/url] cheap snapbacks free shipping b flca[url=]snapback hats wholesale[/url] snapback hats wholesale o eipy[url=]wholesale baseball caps[/url] wholesale baseball caps c egul[url=]cheap hats[/url] cheap hats b rzny [url=]cheap hats[/url] cheap hats k nhgm [url=]cheap snapback hats[/url] cheap snapback hats p vqzk[url=]cheap snapbacks online[/url] cheap snapbacks online l itzx[url=]wholesale fitted hats[/url] wholesale fitted hats m lbrf[url=]snapback wholesale[/url] snapback wholesale y aroh[url=]cheap snapbacks[/url] cheap snapbacks p yeda

  • jowpwv

    Posted by Suttonktu on 03/30/2013 09:25pm

    ray ban sunglasses sale,Ah, Ah, how, how to do ... a lot, a lot of blood A ...... really a lot of blood ... how do ... he would not be dead ...... Bi Luo heart like caught a savior like pulling A large Q, shaking hands could not. A large Ah never seen Luo Bi heart so went to pieces, and always felt whenever she can cool thinking, and then come up with a solution, Atai Li engraved to appease the right, he's okay. ray ban caravan first torn his clothes behind, or to the time the wound condensation on bad off! To torn clothes! Luo the Pik heart immediately flew beside Qi Zhen Yu, panic tear clothes, but how do not tear open, and looked at the second A large, Aer Li engraved understand past Luo Bi heart aside, while comforting to say, all right, Pitt heart sister, brother in it oakley sunglasses outlet, he fights not bandaging wounds but very powerful, rest assured.Small captain's opinion the very glorious unanimously approved Ah have never eaten a whack chicken, but firmly believe that even without the goodies to Luo cook will be delicious hands very creative oakley sunglasses cheap. Luo Bi heart Ah to elect only when the old chicken to slaughter to the hair, you pick the two best spots fish and wine, onions, ginger, covered with bamboo shoots and bacon into the Steamer steamed, and chose steak chopped into two, taking a dip in soy, wolfberry, burning pot of oil, add the ginger slices to the smell, the steak fry until half cooked, then go to the oil, and soy together into the pot, add water, boil scoop out into the casserole, and simmer with cushions toot on a small coal stove. So the little captain again from the peeler workers promoted to light a fire workers sat on the bench looking at the front of the little coal stove stay. ray ban sunglasses in addition to chicken only spot fish ah?

  • Loading, Please Wait ...

Leave a Comment
  • Your email address will not be published. All fields are required.

Top White Papers and Webcasts

  • As all sorts of data becomes available for storage, analysis and retrieval - so called 'Big Data' - there are potentially huge benefits, but equally huge challenges...
  • The agile organization needs knowledge to act on, quickly and effectively. Though many organizations are clamouring for "Big Data", not nearly as many know what to do with it...
  • Cloud-based integration solutions can be confusing. Adding to the confusion are the multiple ways IT departments can deliver such integration...

Most Popular Programming Stories

More for Developers

RSS Feeds

Thanks for your registration, follow us on our social networks to keep up-to-date