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)
     {
        CDialog::DoDataExchange(pDX);
        //{{AFX_DATA_MAP(CCharityReportDlg)
        DDX_Control(pDX, IDC_LIST, m_List);
        //}}AFX_DATA_MAP
     }
                
  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;
		pDC->FillRect(&labelRect,&labelBrush);

		// 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 );

		pDC->SetTextColor(colorTextSave);
		pDC->SetBkColor(colorBkSave);

		return;
	}

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

		return;
	}

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

		return;
	}
}

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);
	SetItemData(index,color);
}

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



Comments

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

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

    [url=http://www.rettetangnewsnorge.com/beste-ghd]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=http://www.rettetangnorgenews.net/]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=http://www.rettetangnewsnorge.com/falske-ghd]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!

    Reply
  • Much more episode with freak beats

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

    [url=http://www.headphonescheaponlineaustralia.com/]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=http://blog.cheapbeatsbydre.co.nz/]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=http://www.headphonescheaponlineaustralia.com/]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.

    Reply
  • 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 http://www.vimaxofficial.com for a lot of info about the Vimax Pills. flf52013

    Reply
  • 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!

    Reply
  • 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

    Reply
  • 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=http://hunter-rain-boots.webnode.jp]ハンターレインブーツ[/url] hBz [url=http://hunterrainbootsjp.webnode.jp]レインブーツメンズ[/url] i UwxUla EsuJ [url=http://hunter-boots8.webnode.jp]レインブーツメンズ[/url] jd Z [url=http://rain-boots-men.webnode.jp]ブーツ[/url] ca [url=http://hunter-rain-boots-ja.webnode.jp]レインブーツ[/url] AuiDgnIok P[url=http://rainshoesja.webnode.jp]ブーツ[/url] sgTvgZgfVt [url=http://ja-hunter-rain-boots.webnode.jp]ハンター長靴[/url] c DreGsn [url=http://rain-boots-popular.webnode.jp]レインシューズ[/url] Nkm [url=http://rain-boots-men6.webnode.jp]ハンターレインブーツ[/url] Zyz Mic [url=http://jahunterrainboots.webnode.jp]ハンター長靴[/url] Qau

    Reply
  • 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=http://www.hollistercorfrance.fr]hollister france[/url] and regions worldwide from authorised retailers. The chemicals found included high levels of toxic phthalates [url=http://www.abercrombiesfrancevparise.fr]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=http://www.airjordanfrpaschere.fr]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=http://www.abercrombieufrancersoldes.fr]abercrombie[/url] a covey of the products tested. I secure recently fallen in about the life of with the denomination SkunkFunk which [url=http://www.airjordanspasuchere.fr]air jordan pas cher[/url] features on style-is.co.uk 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=http://www.hollisterfrancevmagesin.fr]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=http://www.abercrombievandfitchuks.co.uk]abercrombie uk[/url] was disinterested mastery than I expected, can’t stand wrong to portion frightfully a before you can say 'jack robinson' [url=http://www.monclerfrancermagasinsfr.fr]moncler[/url]! It seems like that’s all I’ve been saying to you guys lately. But [url=http://www.airjordanzchaussuren.com]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=http://www.michaelukorsua.com]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=http://www.hollisterucoboutiquer.fr]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=http://patrimoine.agglo-troyes.fr/BAM/louboutinpascher.html]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.

    Reply
  • 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

    Reply
  • snapbacks for cheap

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

    [url=http://wholesalefittedhat.webs.com]snapbacks wholesale[/url] snapbacks wholesale g czdq [url=http://snapbackswholesalezone.webs.com]hats wholesale[/url] hats wholesale a xuyy[url=http://bestbaseballcap.webs.com]wholesale baseball caps[/url] wholesale baseball caps s lpmx[url=http://cheapsnapbacksforsalezone.webs.com]cheap snapbacks online[/url] cheap snapbacks online x wrll[url=http://goodsnapbackhatscheap.webs.com]cheap snapbacks[/url] cheap snapbacks h geoi[url=http://goodsnapbackhatscheap.webs.com]cheap snapbacks free shipping[/url] cheap snapbacks free shipping g kxpj [url=http://cheaphatsmall.webs.com]cheap snapback hats[/url] cheap snapback hats k cdkf [url=http://bestbaseballcap.webs.com]wholesale baseball caps[/url] wholesale baseball caps n omnp[url=http://cheapsnapbacksforsalezone.webs.com]cheap snapbacks free shipping[/url] cheap snapbacks free shipping b flca[url=http://snapbackswholesalezone.webs.com]snapback hats wholesale[/url] snapback hats wholesale o eipy[url=http://bestbaseballcap.webs.com]wholesale baseball caps[/url] wholesale baseball caps c egul[url=http://cheaphatsmall.webs.com]cheap hats[/url] cheap hats b rzny [url=http://cheapsnapbackshat.webs.com]cheap hats[/url] cheap hats k nhgm [url=http://goodsnapbackhatscheap.webs.com]cheap snapback hats[/url] cheap snapback hats p vqzk[url=http://cheapsnapbacksforsalezone.webs.com]cheap snapbacks online[/url] cheap snapbacks online l itzx[url=http://snapbackhatwholesale.webs.com]wholesale fitted hats[/url] wholesale fitted hats m lbrf[url=http://snapbackswholesalezone.webs.com]snapback wholesale[/url] snapback wholesale y aroh[url=http://cheaphatsmall.webs.com]cheap snapbacks[/url] cheap snapbacks p yeda

    Reply
  • http://www.nikeairmaxwr.com/ jowpwv

    Posted by http://www.nikeairmaxwr.com/ 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?

    Reply
  • Loading, Please Wait ...

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

Top White Papers and Webcasts

  • Managing your company's financials is the backbone of your business and is vital to the long-term health and viability of your company. To continue applying the necessary financial rigor to support rapid growth, the accounting department needs the right tools to most efficiently do their job. Read this white paper to understand the 10 essentials of a complete financial management system and how the right solution can help you keep up with the rapidly changing business world.

  • Event Date: April 15, 2014 The ability to effectively set sales goals, assign quotas and territories, bring new people on board and quickly make adjustments to the sales force is often crucial to success--and to the field experience! But for sales operations leaders, managing the administrative processes, systems, data and various departments to get it all right can often be difficult, inefficient and manually intensive. Register for this webinar and learn how you can: Align sales goals, quotas and …

Most Popular Programming Stories

More for Developers

Latest Developer Headlines

RSS Feeds