Using text callbacks

If you store you application data and you wish to save some time and memory, you can have the list ask your application for the strings to display in the list on the fly, instead of having the list store the strings explicitly. This will reduce the amount of memory your final app needs and will make filling and deleting the list contents quicker, at the expense of slightly slower display time. (If you are displaying several thousand items in the list, the time saved in filling and cleaning the list more than makes up for fractionally slower display). Furthermore, list sorting can become lightning fast.

Suppose your data is stored in your app in structures "ItemStruct" declared:

typedef struct {
	int nItemNo;
	CString strName;
} ItemStruct;

and each structure is stored in an array, list or map. The easiest way to let the list know about each item is to store a pointer to each item in the lParam field of the LV_ITEM structure you pass to the CListCtrl::InsertItem function.

Firstly, when you add a new item to the list you should set the LVIF_PARAM bit in the mask field of your LV_ITEM structure that you are using. This lets the list know that the lParam field of your LV_ITEM contains data.

You may want to create a helper function to add a new item to the list like:

BOOL CMyListCtrl::AddItem(ItemStruct* pItem, int nPos /* = -1 *
)
{
	int nNumItems = GetItemCount();
	int nInsertPos = (nPos >= 0 && nPos <= nNumItems)? nPos : nNumItems;

	LV_ITEM Item;
	Item.lParam	  = (LPARAM) pItem;		// Store the pointer to the data
	Item.pszText  = LPSTR_TEXTCALLBACK;		// using callbacks to get the text
	Item.mask	  = LVIF_TEXT | LVIF_PARAM;	// lParam and pszText fields active
	Item.iItem	  = nInsertPos;			// position to insert new item
	Item.iSubItem = 0;
	
	if (InsertItem(&Item) < 0) 
		return FALSE;					
	else
		return TRUE;
}

The LPSTR_TEXTCALLBACK value for the pszText field tells the list that it should use callbacks to get the text to display, instead of storing the text itself. Every time the list needs to display text, it sends a LVN_GETDISPINFO. We don't add text for the subitems, since they will be dealt with in the LVN_GETDISPINFO handler as well.

You need to handle the windows notification LVN_GETDISPINFO using the following:

BEGIN_MESSAGE_MAP(CMyListCtrl, CListCtrl)
	//{{AFX_MSG_MAP(CMyListCtrl)
	ON_NOTIFY_REFLECT(LVN_GETDISPINFO, OnGetDispInfo)
	//}}AFX_MSG_MAP
END_MESSAGE_MAP()

and have an accompanying function declared in you class definition:

class CMyListCtrl 
{
// .. other declarations

// Generated message map functions
protected:
	//{{AFX_MSG(CMyListCtrl)
	afx_msg void OnGetDispInfo(NMHDR* pNMHDR, LRESULT* pResult);
	//}}AFX_MSG
};

The handler function should look something like:

void CMyListCtrl::OnGetDispInfo(NMHDR* pNMHDR, LRESULT* pResult) 
{
	LV_DISPINFO* pDispInfo = (LV_DISPINFO*)pNMHDR;

	if (pDispInfo->item.mask & LVIF_TEXT)
	{
		ItemStruct* pAppItem = (ItemStruct*) pDispInfo->item.lParam;
		CString strField = QueryItemText(pDispInfo->item.iItem, 
							   pDispInfo->item.iSubItem);
		LPTSTR pstrBuffer = AddPool(&strField);	

		pDispInfo->item.pszText = pstrBuffer;
	}	
	*pResult = 0;
}

The NMHDR variable contains the list view display info, which in turn holds a LV_ITEM member specifying the item and subitem it's after, and what sort of info it's after. In our case we are only specifying text, so we only deal with notifications where the pDispInfo->item.mask equals LVIF_TEXT. We get a pointer to our Apps data through the lParam field of LV_ITEM, and from this we get a text representation of our data (I'm using another helper function "QueryItemText" implemented as

// returns a CString representation for the data in row nRow, column nCol
CString CMyListCtrl::QueryItemText(int nRow, int nCol)
{
	CString strField;
	ItemStruct* pAppItem = (ItemStruct*) GetItemData(nRow);
	if (!pAppItem) return strField;

	switch (nCol) {
		case 0:	strField.Format("%d",pAppItem->nItemNo);	break;
		case 1: strField = pAppItem->strName;			break;
		default: ASSERT(FALSE);
	}

	return strField;
}

The main reason I use the "QuesryItemText" function is that since we are now using text callbacks, functions like CListCtrl::GetItemText no longer work. If you use GetItemText (for instance in TitleTips or InPlaceEdit's) then you must replace them with QueryItemText in order for them to work. The two lines:

	LPTSTR pstrBuffer = AddPool(&strField);	
	pDispInfo->item.pszText = pstrBuffer;

in the OnGetDispInfo function were taken from Mike Blaszczak's program "ApiBrow" (get it either online or from his book "Proffessional MFC with Visual C++ 5"). It handles the bizarre situtation that the list control requires the buffer you pass back from the OnGetDispInfo to be valid for 2 more LVN_GETDISPINFO notifications. His solution was a simple caching to store sufficient copies so the list control doesn't have a cow. It goes something like this:

LPTSTR CMyListCtrl::AddPool(CString* pstr)
{
	LPTSTR pstrRetVal;
	int nOldest = m_nNextFree;

	m_strCPool[m_nNextFree] = *pstr;
	pstrRetVal = m_strCPool[m_nNextFree].LockBuffer();
	m_pstrPool[m_nNextFree++] = pstrRetVal;
	m_strCPool[nOldest].ReleaseBuffer();

	if (m_nNextFree == 3)
		m_nNextFree = 0;
	return pstrRetVal;
}

You will need to declare the protected attributes

	CString m_strCPool[3];
	LPTSTR	m_pstrPool[3];
	int	m_nNextFree;

in your class definition.

And that's all there is to it!

One advantage of storing the data in the lParam field is that sorting become very quick. A column sort function as already been provided in in the MFC programmers sourcebook. It is prototyped:

BOOL CMasterListCtrl::SortTextItems(int nCol, BOOL bAscending, 
					int low /*= 0*
, int high /*= -1*
 );

I will ignore the high and low parameters (sorry!) and instead implement a different version: (see the docs on CListCtrl::SortItems for details)

typedef struct {
	int nColumn;
	BOOL bAscending;
} SORTINFO;

BOOL CMasterListCtrl::SortTextItems(int nCol, BOOL bAscending)
{
	CWaitCursor waiter;

	SORTINFO si;
	si.nColumn = m_nSortColumn;
	si.bAscending = m_bSortAscending;
	return SortItems(CompareFunc, (LPARAM) &si);
}

int CALLBACK CompareFunc(LPARAM lParam1, LPARAM lParam2, LPARAM lParamSort)
{
	ItemStruct *pItem1 = (ItemStruct*) lParam1;
	ItemStruct *pItem2 = (ItemStruct*) lParam2;
	SORTINFO* pSortInfo = (SORTINFO*) lParamSort;
	ASSERT(pItem1 && pItem2 && pSortInfo);

	int result;
	switch (pSortInfo->nColumn) {
		case 0: if (pItem1->nItemNo < pItem2->nItemNo) 
					result = -1;
				else if (pItem1->nItemNo == pItem2->nItemNo) 
					result = 0;
				else 
					result = 1;
				break;
		case 1: result = pItem1->strName.Compare(pItem2->strName); 
				break;
		default: ASSERT(FALSE);
	}

	if (!pSortInfo->bAscending) result = -result;
	return result;
}



Comments

  • Pas cher ghd rose est votre meilleur Choirce en 2013

    Posted by xqkwbz122 on 07/16/2013 02:00am

    Collection GHD métallique est la plus récente édition limitée fer portée Tilgiengelig. La nouvelle Série Or mince élaboration d'un REACH est Lansert pour Noël 2012 dans 3 Fabelaktig couleur métallique de tricotage. Ceci Ruby Red Metallic Styler est également livré avec son propre style Svart vattert poche résistant à la chaleur Ce tige rouge droit a un double plaines spenning signifie que vous pouvez obtenir ytelse cohérente dans le monde idéal lorsque vous allez sur votre Reiser. Aussi avec une innebygd en mode veille de votre tige droite sakte flux begynne de cordes segments bas casseroles 30 minutes pour å bli Brukt - sauver vous vous inquiétez de savoir si vous avez Slatt eux! [url=http://ghdpascherfer.hpage.com/]lisseur ghd[/url] et est parfait pour le curling, le rouissage ou vagues. Bien sûr, il a toutes les grandes funksjonene dans GHD Classique Or comme un funksjonen auto-sommeil, les universités vendent spenning pour bruk sur Reiser, et un long câble d'alimentation supplémentaire pour les simples litt glamour use.Add à coiffer routine avec la collection métallique ghd. [url=http://ghdpascherfer.hpage.com/]ghd lisseur prix[/url] Ces dernières strykejern GHD viennent avec un bonbon de protection suscité que vous pouvez sauter quand vous avez fini un protège votre tige droite. Glam Svart vattert sac de roulis est l'accessoire parfait pour Red Metallic GHD. Et d'un être complètement résistant à innsiden rouleau derrière gir deg aussi un tapis résistant à la chaleur pour y distillat une Trygg lieu de repos pour køllene tout en bruk.Prøver y choisir la beste Flatt fer ou redresseur peuvent être skremmende. Comment vite qui ne sera pas Bryte, n'endommagera pas les cheveux et va peiner le plus rapide? Je l'ai fait pour jobben deg, y enquêter sur la Flatt fer beste et défrisants sur le marché. Vous aurez nageoire coûteux Flatt fer arguments affection et le strykejern de flate plus raisonnable ne sera pas Bryte à deg.

    Reply
  • clarisonic mia can resolve your common antiseptic

    Posted by iouwanzi on 06/05/2013 08:06pm

    [url=http://www.miaclarisonicaustralia.org/]clarisonic mia[/url] i hvert fald set er en god musik altid være påkrævet, og hovedtelefonerne som Dre beats forbedrer sådan musik, så du har lyst til himlen. I denne artikel vil vi diskutere, hvor langt disse bemærkelsesværdige hovedtelefoner (Dre beats hovedtelefoner) er i stand til, og hvordan strålende det kan støtte dig til at få essensen af musikken. For din korte viden – Monster har formået at kombinere stil med funktionalitet i Dr. Dre udvalg af hovedtelefoner understøtter disse ikke blot at se godt, men også at gøre lydkvaliteten endnu bedre. Hvis du kigger ind i dens specifikationer så du kan indse det, at de beats fra Dre hovedtelefoner lyd er altid velafbalanceret med en varm mellemtone og dunkende bas. [url=http://www.miaclarisonicaustralia.org/]clarisonic mia australia[/url] Vi har været i stand til at tilbringe cirka en time med systemet, og vi har helt ærligt komme væk meget imponeret. Enheden føles meget robust, med en stiv metalgitter og soft-touch belægning omkring resten af sit ydre. Det føles meget behageligt at holde i en hånd, og vil nemt passe i en jakkelomme. Faktisk en af vores eneste oprindelige klager er, at den medfølgende regnskabsmæssige skallen ikke efterlader nogen plads til de medfølgende kabler. Alle knapper har en blød, let clicky taktilitet, som også hjælper til sin præmie føler. Brug det i første omgang sammen med en af Beats ‘on-hånd Jamboxes i et kablet A / B sammenligning Jambox kom ud lyde som en forvrænget, rumlende rodet op mod pille – vi havde endda en rep bringe en anden enhed bekræfter, at det var ikke en dud. Hvis det ikke var nok, p-piller også formået at få meget højere, opholder sig temmelig ren (i sammenligning), og uden at rumlen på bordet som den Jambox gjorde meget lidt. Som en tredobbelt-check foranstaltning, senere kom vi op med et lignende resultat med vores in-house-enhed Logitechs $ 99 UE mobil boombox – en højttaler vi finder sammenlignelige med lyd, hvis en smule bedre, end Jambox. [url=http://www.miaclarisonicaustralia.org/]clarisonic mia online[/url] Ligegyldigt om nogen efterspørgsel en ny hookup vedrørende personlig ansætte i dit hus samt med henblik på at venstre arm din nuværende lille vedrørende institution, dette er den meget specielle, der vil sikre en favorit BIII øretelefoner spørgende, Min ægtefælle og jeg gravede lidt dybere involveret med det sammen med min ægtefælle og jeg, din ml i allexpect en ny, netop hvad jeg lige kigger ind nedenfor besøgende i de mange standard fornødenheder. Sandheden er, jeg er bare planlægning for dig at adskille idéen sammen i dit tilfælde for at sige det kort sort.

    Reply
  • La más completa destacados ghd

    Posted by wanzilucky on 06/05/2013 07:59pm

    [url=http://www.planchasespanaghdtop.net/plancha-pelo-ghd/]plancha pelo ghd[/url] PINK, la edición más especial y solidaria de ghd este año evoca a Oriente. Hoy hacemos un viaje de belleza solidario hasta Oriente con la edición especial de ghd PINK Cherry Blossom. Tomando como inspiración toques florales de inspiración oriental, la styler ghd PINKCerry Blossom se salpica de motivos en diferentes tonos de rosa. Esta nueva edición limitada, que se lanza anualmente y de manera global en apoyo a la investigación oncológica del cáncer de mama, cuenta en España con el apoyo de la actriz Elsa Pataky que por tercer año consecutivo se involucra en el proyecto solidario de ghd. [url=http://comprar-ghd.manifo.com/]Comprar ghd[/url] Cumplir con este tipo de medidas cuando usted se encuentra de compras alrededor perteneciente a GHD planchas de cerámica junto con usted puede ser que tenga un verdadero producto o servicio.Otra característica tan especial de los alisadores de GHD es el ajuste automático de calor. Debido a esta característica especial funcional el riesgo de sobrecalentamiento o la quema de los cabellos. Por lo tanto, se ve que los alisadores de pelo GHD tomar un buen cuidado de su cabello. Convirtiéndose así en la mayor parte de un elemento necesario para todos los hogares. [url=http://www.planchasespanaghdtop.net/]GHD Plancha España[/url] Por lo visto la reina indiscutible de los foros es la GHD, pero mi duda es ¿es recomendable para un tipo de pelo como el mío una plancha sin regulador de temperatura? Mi pelo es muy fino, algo quebradizo y muy poroso. Para más inri llevo mechas con lo que tengo las puntas algo secas, pero las raices grasas y sin volumen. Tengo el pelo muuuy encrespado.Según dicen las GHD son las que más protegen el pelo pero, ¿también en un caso como el mío?Yo había pensado comprarme una con regulador de temperatura y utilizarla a 160 o 170º, pero las que he probado me siguen dejando el pelo encrespado y con las puntas secas, así que acabe devolviendolas (solac, rowenta, braun).

    Reply
  • Prevail the kindest earphones put into monster beats

    Posted by motherdhmm on 06/04/2013 02:53am

    [url=http://www.headphonescheaponlineaustralia.com/]beats by dre Australia[/url] The humane more Ghoulishness Beats Solo headphones: The Beats Solo before Dr. Dre Headphones from Giant offer a smart, compact, and stable design that lends itself well to on-the-go use.The cable is ultranice and features an integrated mic, iPod controls, and size rocker.Bass is mammoth, and the carton includes a clever carrying case. because of its lilliputian immensity, indulgent to convey, so the green materials needed in the manufacturing course of action more in the vend prices were relatively base, cheaper then Beats by Dr. Dre Studio Diamond Headphone the Red in Australia, as long as you keep 150USD that, you can not the be paid it from the Beats beside Dr. Dre online. [url=http://www.headphonescheaponlineaustralia.com/beats-pro-c-66_68_75.html]beats Pro[/url] You can take it that hazard on beats by dr.dre headphone and harken to to the magnificent music honourable like the singer is fixed before you and singing on you. We put on the market beats sooner than dre in a despicable consequence,Credit it or not, Beats dre australiaIs your ideal choice. What is more, Beats through dre headphones is the following of every music follower, I know you will not wish for it! We poor beats by dre headphones think it reverberate mark is entirely major, specially over-valued, well recommended. [url=http://blog.cheapbeatsbydre.co.nz/monster-headphone]monster beats headphone[/url] Deformity Beats side, as an alternative any degree of payment any grumble files incline to be along the way to come by textile to abide all people within nearly closeness to be clever to well. you can contain the difficulties when any individual own within your is better than through dre come by of your vigour skinflinty dr dre beats, essentially any thoughts attend to to be organising truly .

    Reply
  • GHD glattejern er helt unike og det er ogsÃ¥ derfor de sælger sÃ¥ godt

    Posted by motherdhmm on 05/30/2013 04:55am

    [url=http://www.buy-beatsdrdre.com/]beats by dre australia[/url] ghd fladjern også kendt som elektriske krydsfiner, er krydsfiner populært kaldes, er opvarmet af aktuelle ghd glattejern for MCH eller PTC varmelegeme eller varmt wire, aluminium eller keramik plade til at overføre varme. ghd glattejern, Guming Si Yi er at glatte håret, håret gennem varmeelement for varme, blødgøre, og derefter afkølet for at opnå formålet med glat hår. Nu ghd glattejern, glatte begge dele, og kan trække lydstyrken. Ghd glattejern før, den største bruger er en professionel salon barber, Europa og Amerika fra 2007 personer er kommet på hjemmemarkedet, til hår derhjemme kan være en SPA. Ghd glattejern vil nu ind på det danske hjemmemarked, vil være en væsentlig produkter til personlig pleje, ligesom kamme den samme popularitet. [url=http://www.blog.cheapbeatsbydre.co.nz/]beats by dre nz[/url] Ghd sammenlignet med tidligere produkter, denne generation af glat hår med ekstra slankt design, mode af den ydre uanstændige og nogle geniale nye unikke sted i glat hår, hårpleje og styling har gjort store forbedringer. GHD IV styler primære unikt sted: mere vækst i den keramiske varme plader. MK4 Ghd Opvarmningen er færdig vil der være et bip for at gøre dig opmærksom på at organisere ansøgning. Unik og holdbart cover design, ikke noget på egen hånd efter 15 minutter lukkede specielle kabler designet til at opretholde den fugtige keramiske feber tabletter fra skade på miljøet. [url=http://www.buy-beatsdrdre.com/]beats by dre[/url] Nu enden af elementet er normalt fluorescerende, og jeg har brug for glat hår. Processen tager kun fem minutter, kan dit hår vende tilbage til den oprindelige Express. Brug derefter nogle hår spray ghd hår glat hår, især hår til at beskytte håret jern strøm af overhedet temperatur på fødevarer farer, og kan hjælpe med dit hår er uønskede ioner med høj teknik. Det er delikat og ren. GHD Danmark emballage er ofte særligt, plus de er nemme at håndtere.

    Reply
  • Launch 2013 a new color schematic Nike Air Max shoes

    Posted by Tufffruntee on 04/25/2013 01:48am

    Qualifying series Nike Atmosphere Max HomeTurf metropolis recently completely comes up, this series in the exemplary Tune Max shoes to London, Paris and Milan [url=http://www.nikeskoroutlet.se/nike-air-max-90-c-1/]air max 90 billigt[/url] the three paid glorification to the iconic city of Europe, combined with the characteristics of the three cities, Bearing Max 1 HYP,Current Max 90 HYP,Air Max 1 and shoes such as Music pretension Max 95, combined with the Hyperfuse, as by a long chalk as a order of materials, such as suede, Whether you require functioning or retro-everything. It seems to me that more than Nike [url=http://www.nikeskornatet.se/nike-lunarglide-4-c-25/]nike lunarglide 4 dam[/url] shoes all supernova dissimulate sanctioned signature shoe series, and NSW series, all star color system of the original Air Max Hyperposite exposure. Ray daybreak brown vexed, hyperfuse, swoosh, and are attached at the cessation of the yellow/orange gradient split details, lining is a Galaxy in [url=http://www.airmax90rea.se/nike-air-max-bw-c-5/]nike air max bw[/url] orange prototype garter, acutely beautiful.

    Reply
  • Nike Draught Max+instagram, desire you take the color to wear on your feet!

    Posted by madytreathy on 04/24/2013 10:42pm

    Call to mind in 2008, if not earlier, when Nike launched winning of the independent shoe color projects, the watchword "Bound Your Colours", "Nike PhotoiD" layout, [url=http://fossilsdirect.co.uk/glossarey.cfm]nike huarache free[/url] effect has not been as fervent as expected. Have in mind, 2008 Canon IXUS 80 IS Digital prankster arcade but contrariwise 8 million pixels, Nokia, the facile phone market-place is the exclusively governorship, NikeiD was support to color in the photos as a basis in return sneakers custom color, although interesting, but does bother some. Instagram which make this thing hold up to ridicule and fundamental, Nike PHOTOiD homeopathic upgrade customization services, recently [url=http://markwarren.org.uk/property-waet.cfm]air max 90 uk[/url] released a fresh plan. That such iD can you utensil pictures as instagram account shoe color, little while volunteer Nike Air Max shoes and Nike Refresh Max 1, Nike Affectedness Max 90 953 options. Interested in children's shoes, you [url=http://markwarren.org.uk/goodbuy.cfm]nike free run uk[/url] can always go's proper website photoid.Nike.com, in beyond to flick through other people's creative work, or you can try to upload your own instagram photo, build your own Nike Mood Max.

    Reply
  • Virtual ListCtrl and Curent

    Posted by Legacy on 07/04/2002 12:00am

    Originally posted by: Ashmarti

    What is difference between Vitual List Control and presented here method??? I think that is the same.
    Is not it?

    Reply
  • Something wrong with function AddItem...

    Posted by Legacy on 07/26/2001 12:00am

    Originally posted by: Aleksey Ulitsky

    Hi all,
    Probably in the function AddItem is missing an assignment of the pointer ItemStruct *pItem. It should be saved in the in the item if the list control as it's data. Therefore, I changed last lines like folowing:

    ...........................................//AddItem
    if ( index< 0)
    return FALSE;
    else{

    return SetItemData(index, (DWORD)pItem );
    }
    }///////////////////////////////// end function....

    Sincerely,
    Aleksey Ulitsky

    Reply
  • Test

    Posted by Legacy on 12/01/2000 12:00am

    Originally posted by: Bill

    This is a test post

    Reply
  • Loading, Please Wait ...

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

Top White Papers and Webcasts

  • Live Event Date: September 10, 2014 @ 11:00 a.m. ET / 8:00 a.m. PT Modern mobile applications connect systems-of-engagement (mobile apps) with systems-of-record (traditional IT) to deliver new and innovative business value. But the lifecycle for development of mobile apps is also new and different. Emerging trends in mobile development call for faster delivery of incremental features, coupled with feedback from the users of the app "in the wild". This loop of continuous delivery and continuous feedback is …

  • Packaged application development teams frequently operate with limited testing environments due to time and labor constraints. By virtualizing the entire application stack, packaged application development teams can deliver business results faster, at higher quality, and with lower risk.

Most Popular Programming Stories

More for Developers

Latest Developer Headlines

RSS Feeds