// The pointer to my list box.
extern CListBox* pmyListBox;
// Find the longest string in the list box.
CString str;
CSize sz;
int dx = 0;
TEXTMETRIC tm;
CDC* pDC = pmyListBox->GetDC();
CFont* pFont = pmyListBox->GetFont();
// Select the listbox font, save the old font
CFont* pOldFont = pDC->SelectObject(pFont);
// Get the text metrics for avg char width
pDC->GetTextMetrics(&tm);
for (int i = 0; i < pmyListBox->GetCount(); i++)
{
pmyListBox->GetText(i, str);
sz = pDC->GetTextExtent(str);
// Add the avg width to prevent clipping
sz.cx += tm.tmAveCharWidth;
if (sz.cx > dx)
dx = sz.cx;
}
// Select the old font back into the DC
pDC->SelectObject(pOldFont);
pmyListBox->ReleaseDC(pDC);
// Set the horizontal extent so every character of all strings
// can be scrolled to.
pmyListBox->SetHorizontalExtent(dx);
int SetListboxHorz( CListBox &listbox )
{
CString Name;
CSize Size;
CDC * DeviceContent = 0;
long Width = 0;
long Count = 0;
Count = listbox.GetCount();
if ( Count )
{
DeviceContent = listbox.GetDC();
for ( long Index = 0; Index < Count; Index++ )
{
listbox.GetText( Index, Name );
Size = DeviceContent->GetTextExtent( Name );