Changing row height in owner drawn control


When you change the font of a list view control, the control or its parent window does not get a chance to respecify the height of the rows. No WM_MEASUREITEM message is sent to the controls parent window. The net effect is that when the font is changed for the control, the row height is no longer valid.

Here's a work around that forces the WM_MEASUREITEM message to be generated.

Step 1: Add handler for WM_SETFONT

The WM_MEASUREITEM message is sent when the control is created. Fortunately this message is also sent whenever the control is resized. Since we want the row height to be adjusted when the font changes, what better place to do thin than in the WM_SETFONT handler. In OnSetFont() we fool Windows into thinking that the window size of the control has changed. We do this by sending the WM_WINDOWPOSCHANGED message to the control which then gets handled by the default window procedure for the control. Note that we haven't specified the SWP_NOSIZE flag and we set the width and height field in the WINDOWPOS structure equal to the existing dimension.

For some reason, the Class Wizard did not have the WM_SETFONT message in its list of window messages. You will have to add the message map entry yourself. It is important to place the entries outside of the block used by the Class Wizard, otherwise the next you make any change with the wizard, our manual changes will be lost.

// In the header file
	//{{AFX_MSG(CMyListCtrl)
	:
	:
	//}}AFX_MSG
	afx_msg LRESULT OnSetFont(WPARAM wParam, LPARAM);
	afx_msg void MeasureItem ( LPMEASUREITEMSTRUCT lpMeasureItemStruct );
	DECLARE_MESSAGE_MAP()


//////////////////////////////////////////////////////////////////////
// In the cpp file
BEGIN_MESSAGE_MAP(CMyListCtrl, CListCtrl)
	//{{AFX_MSG_MAP(CMyListCtrl)
	:
	:
	//}}AFX_MSG_MAP
	ON_MESSAGE(WM_SETFONT, OnSetFont)
	ON_WM_MEASUREITEM_REFLECT( )
END_MESSAGE_MAP()


LRESULT CMyListCtrl::OnSetFont(WPARAM wParam, LPARAM)
{
	LRESULT res =  Default();

	CRect rc;
	GetWindowRect( &rc );

	WINDOWPOS wp;
	wp.hwnd = m_hWnd;
	wp.cx = rc.Width();
	wp.cy = rc.Height();
	wp.flags = SWP_NOACTIVATE | SWP_NOMOVE | SWP_NOOWNERZORDER | SWP_NOZORDER;
	SendMessage( WM_WINDOWPOSCHANGED, 0, (LPARAM)&wp );

	return res;
}

Step 2: Add handler for WM_MEASUREITEM

Since we want our CListCtrl derived class to be modular, we will handle the WM_MEASUREITEM message within this class. The message however, is sent to the parent window, so we use message reflection. Again, the Class Wizard is not much help. We have to manually add the entry in the message map and update the header file. See the code snippet in step one for this.
void CMyListCtrl::MeasureItem ( LPMEASUREITEMSTRUCT lpMeasureItemStruct )
{
	LOGFONT lf;
	GetFont()->GetLogFont( &lf );

	if( lf.lfHeight < 0 )
		lpMeasureItemStruct->itemHeight = -lf.lfHeight; 
	else
		lpMeasureItemStruct->itemHeight = lf.lfHeight; 
}



Comments

  • Existente ghd para encantadora que

    Posted by hkxqar920 on 07/17/2013 07:06pm

    La ciudad industrial del siglo XIX y la construcción de puertos, el rápido desarrollo económico, la convierten en la segunda mayor ciudad del país, Aarhus es una ciudad comercial Jutlandia, Noruega y Dinamarca también se conectan otros medios de transporte de la ciudad hub.Clean y hermosa ciudad de Aarhus, el paisaje rural de Europa, El edificio formado número de único e innovador bygninger.fordi diseño de su ubicación geográfica y los residentes locales entusiastas culture.Aarhus amor siempre ha sido el centro cultural de Jylland.Vores línea planchas ghd para la venta, la cerámica lineal, muy bueno para proteger tu cabello se ve muy buena resistencia al calor. Rápidamente se calienta, en el transcurso de 2-3 minutos para alcanzar la temperatura deseada. Voltaje seguro, fácil de usar que en cualquier país. La plancha de pelo ghd es el más barato. Tenemos una amplia gama de productos y colores. Si te gusta, por lo que comprar lo correcto. [url=http://comprarghd.webgarden.com/]GHD España[/url] Esto es a menudo debido a sus herramientas de diseño, y ahora Barber Shop es la peor opción, ya que ahora tienen que hacer cola, si se podía hacer hasta que el cabello, se puede sentir el efecto no es muy buena, lo que afecta Imagina tenías el pelo. Cómo hacer esto, no quiero volver a hacerlo otra vez? Planchas ghd que no lo hacen porque diseñador tiene un concepto único diseñado para permitir a más personas a hacer su peinado favorito, sino también a sí mismo. Planchas ghd ahora, es que la gente piensa que es una varita mágica. Capaz de sorprenderme cada øjeblik.Mange gente compra en línea ghd, la razón principal es barato, pelo ghd tan barato cada vez más popular, y proporcionamos a los expertos venta ghd más profesionales, tenemos un equipo fuerte dedicada plancha ghd adquisición, presentación, promoción, etc, que se actualizará cada día, productos alisadores GHD todos los días, terminando nuestros pedidos ghd. Así usted compra nuestros productos ghd, seleccione su información personal clave. Para más información consulte las preguntas frecuentes, etc. Espero que compras felices en nuestro sitio web [url=http://ghddescuentosonline.npage.de/]planchas ghd[/url] EE.UU. Altid tiltrækker Vores opmærksomhed, vi kan lide Smukke ting, ting Mennesker eller. Så enhver kvinde ønsker al eje mera charmerende og Smukke. Dette kræver, por lo vi hele tiden Gore dig forandring. --- Hver dag vi skifter Toj og kan BAERE forskellige Toj. Dette er kun udseendet af ændringen, kan vi OGSA læse flere Boger. Skift indefra dig selv. Det hår. Sådan Gor du hår. Dette er OGSA en masa af skønhed spørgsmål. Før Begge er ændret. Hombres hvordan hombre Gor den første tipo. Vi El Vendedor ghd glattejern, hår er et godt konverteringsværktøj, kan det konstant ændre hår dit, los hombres ved din egen parte, ikke kun para Barber Shop kan repuesto dig tid, gennem konstant forandring kan du findes para ejer mera hår.

    Reply
  • clarisonic pro 2012 standard in pink

    Posted by iouwanzi on 06/06/2013 11:07am

    [url=http://www.miaclarisonicaustralia.org/clarisonic-mia]clarisonic mia[/url] Victoria Secret 2012, la dernière conférence de maillots de bain sur la belle Miranda Kerr trésor et sexy top model Candice Swanepoel lors de la sélection se tailler un style de grands ghd lisseur cheveux de milliers de féminité sexy. Mannequin ange sexy pour Victoria Secret 2012, la dernière Maillots de bain pour la publicité, [url=http://www.australiaclarisonic.com/]clarisonic mia[/url] Souvent, vous pourriez certainement blâmer la médecine. straightner cheveux babyliss Pour être en mesure de bien déterminer qui sont les premiers hébergeurs sont le soutien cyberespace, vous avez vraiment besoin de prendre du temps, ce qui est malheureusement de vos services, pour explorer avec vous pour la recherche. [url=http://www.miaclarisonicaustralia.org/]clarisonic mia australia[/url] et en plus vous savez quoi ? Cette approche n’est pas presque tous. Est normalement photographié, à peu près chaque période unique, juste par le photographe professionnel populaire particulière ? Certes, le logiciel n’est pas tout un plus petit montant connu Katy.concernant pour lequel vous consacrez une bonne période de 7 jours. Juste pour une partie, Document mis au point plusieurs évolutions dont je parle avant longtemps. Bien sûr, le logiciel peut-être promi ! Toujours juste avant tout cela, Document allait donner à ma propre volonté.

    Reply
  • Nye ghd glattejern, de seneste oplysninger

    Posted by motherdhmm on 05/30/2013 05:16pm

    [url=http://www.blog.cheapbeatsbydre.co.nz/beats-by-dre-headphones]beats by dre headphones[/url] Du kan altid være i løbet af på denne lejlighed fase kunne finder sted GHD hoved af hår styling materiale skal være stand, så du kan chill ud manke. Løsn op låse på indersiden placerer for generating betydeligt lettere din tilgang. Sikre, hvordan den præcise GHD hoved af hår, som gør du hår rustfrit stål dybest set kan holde passende låse, vedroerer en awesome inde. omfattende, har en ideel slut resultatet. Du bør starte for din forklaring, som ved den vitale hår fordi potentiale dog sørge for, af hvilke hår hår styling metal ikke vil tillægger med din bestemt person menneskets hjerne. Generere den nøjagtige et par forskellige alt uden for ens hoved af hår, forbedre de faktiske GHD tresses styling stål desuden at starte, falder der slags støt helt for kun om ethvert forslag. Konstant holde dublere denne tilgang inde i de særlige, en række forskellige andre problemer med låse inden du vælger at få velkendt bruge sammen med waviness. [url=http://www.buy-beatsdrdre.com/]beats by dre[/url] Mange tror at det er nemt nok at vælge et ghd glattejern. Altså når man først har besluttet sig for at man vil have et ghd glattejern og ikke et af de andre mærker inden for glattejern. Men der findes flere forskellige modeller inden for ghd glattejern. Hvilket ghd glattejern du skal vælge afhænger af hvad krav du stiller til det og hvad type hår du har. Har du langt krøllet hår og glatter det ofte, måske endda dagligt, så kan du med fordel vælge en af de brede ghd glattejern der findes. [url=http://www.buy-beatsdrdre.com/category/monster-beats-australia]monster beats australia[/url] GHD Fladjern elsker i øjnene af beskueren, den mest romantiske Valentinsdag i Kina, som udgør deres egen skønhed. Nyt tøj, nye sko, et godt sind er identificeret, så er der tilbringer en vis indsats på håret. Willow-lignende swing, elegant 3000 sort hår, der viser en kvinde, den smukkeste side. Hair Salon Hair Design tænke over, hvad slags kanaler i håret af smukke kvinder over ..

    Reply
  • down

    Posted by yaodebo on 10/11/2006 02:29am

    where to download

    • I'am Minh Tiz

      Posted by minhtiz on 08/02/2008 09:03pm

      Thanks very much!

      Reply
    Reply
  • Row height calculation is not correct. You need to account for external leading.

    Posted by Legacy on 02/23/2004 12:00am

    Originally posted by: A Lee

    You'll find that the row height calculation, as shown, is not quite enough.  This will be evident when your rows are cut off.
    
    

    The problem is that lf.lfHeight gives the height of the font WITHOUT accounting for what is called "external leading," which represents the extra pixels required to write out characters like p and q that have pixels falling under the font's baseline. To get this external leading value, you need to use GetTextMetrics. Just replace the above row height calculation code with the following:

    void MyListCtrl::MeasureItem(LPMEASUREITEMSTRUCT lpmis)
    {
    CClientDC dc(this);
    TEXTMETRIC tm;

    dc.SelectObject(GetFont());
    dc.GetTextMetrics(&tm);

    lpmis->itemHeight = tm.tmHeight + tm.tmExternalLeading;
    }

    Reply
  • How to use

    Posted by Legacy on 12/30/2003 12:00am

    Originally posted by: zxj721

    I Have Insert these Codes in my programe, but I don't know how to use it,thanks

    Reply
  • Szekely Balazs's approach really works! (see the post below)

    Posted by Legacy on 09/26/2003 12:00am

    Originally posted by: Li Zhaoming

    Szekely BalazsSzekely Balazs's approach really works! (see the post below)

    Reply
  • Easy change of height without the ownerdraw shit

    Posted by Legacy on 05/09/2003 12:00am

    Originally posted by: Szekely Balazs

    Use two imaglists:
    ......
    //In definition file:
    CImageList m_imageList1;
    CImageList m_imageList2;
    long m_height1;
    long m_height2;
    CListCtrl m_list;
    ....
    //Somewhere at initialization, m_height1 and m_height2
    //contains the desired heights
    m_height1 = 10;
    m_height2 = 10;

    m_imageList1.Create(1,m_height1,ILC_COLOR4,1,1);
    m_imageList2.Create(1,m_height2,ILC_COLOR4,1,1);
    .....
    //Togle the item height by caling
    m_list.SetImageList(&m_imageList1,LVSIL_SMALL);
    //or
    m_list.SetImageList(&m_imageList2,LVSIL_SMALL);

    //The image index can be set to -1, of the image lists
    //contains some images.

    • How about Report View

      Posted by AliRafiee on 01/25/2005 03:09pm

      How about report view?

      Reply
    Reply
  • Need Demo code

    Posted by Legacy on 01/14/2003 12:00am

    Originally posted by: steven

    I can't insert item,why?

    Reply
  • Another Way to Set row height of list Ctrl

    Posted by Legacy on 08/06/2002 12:00am

    Originally posted by: cuihp

    A Simple way:
    Depend on A ImageList,you can create a ImageList thus:
    CImageList m_ImageList;
    m_ImageList.Create(1,20,ILC_COLOR,1,1);
    Second parameter '20',will decide the row height.

    Inside ListView:
    CListCtrl& lc = GetListCtrl();
    lc.SetImageList(&m_ImageList,LVSIL_SMALL);

    That's All.cuihp

    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: December 11, 2014 @ 1:00 p.m. ET / 10:00 a.m. PT Market pressures to move more quickly and develop innovative applications are forcing organizations to rethink how they develop and release applications. The combination of public clouds and physical back-end infrastructures are a means to get applications out faster. However, these hybrid solutions complicate DevOps adoption, with application delivery pipelines that span across complex hybrid cloud and non-cloud environments. Check out this …

  • CentreCorp is a fully integrated and diversified property management and real estate service company, specializing in the "shopping center" segment, and is one of the premier retail service providers in North America. Company executives travel a great deal, carrying a number of traveling laptops with critical current business data, and no easy way to back up to the network outside the office. Read this case study to learn how CentreCorp implemented a suite of business continuity services that included …

Most Popular Programming Stories

More for Developers

RSS Feeds