void CReportCtrl::AutoSizeColumns()
{
bool bFitWidth=true;
ShowWindow(SW_HIDE);//避免闪烁
SetRedraw(FALSE);
//自动调整宽度
for(int k=0;k<GetColumnCount();k++)
{
// Call this after your list control is filled
if(!GetHeaderCtrl())
return;
if(!bFitWidth)//如果不自动调整最后一列宽度,使得总列宽等于控件宽度,
InsertColumn(GetColumnCount(),"");
int col=k;
int mincol = col < 0 ? 0 : col;
int maxcol = col < 0 ? GetColumnCount()-1 : col;
for (col = mincol; col <= maxcol; col++)
{
SetColumnWidth(col,LVSCW_AUTOSIZE);
int wc1 = GetColumnWidth(col);
SetColumnWidth(col,LVSCW_AUTOSIZE_USEHEADER);
int wc2 = GetColumnWidth(col);
int iFrom=GetTopIndex();
int nCountPerpage=GetCountPerPage();
if(nCountPerpage<=0)
nCountPerpage=GetItemCount();
int iTo=iFrom+nCountPerpage;
int nImgWidth=0;
int iIndent=0;
LVITEM li;
li.mask=LVIF_IMAGE|LVIF_INDENT;
IMAGEINFO ImageInfo;
for(int iItem=iFrom;iItem<iTo;iItem++)
{
li.iItem=iItem;
GetItem(&li);
iIndent=max(li.iIndent,iIndent);
if(li.iImage!=-1)
{
CImageList* pImageList=CListCtrl::GetImageList(LVSIL_SMALL);
if(pImageList->GetSafeHandle())
{
pImageList->GetImageInfo(li.iImage,&ImageInfo);
nImgWidth=max(nImgWidth,ImageInfo.rcImage.right-ImageInfo.rcImage.left);
}
}
}
int wc = max(20,max(wc1,wc2));
if(col==0)
wc+=nImgWidth*(iIndent+1);
else
wc+=nImgWidth;
SetColumnWidth(col,wc);
}
if(!bFitWidth)
DeleteColumn(GetColumnCount()-1);
}
SetRedraw(TRUE);
ShowWindow(SW_SHOW);
}