ListCtrl宽度自适应
While creating a List Control using CListCtrl class, we need to specify the column width for all the columns in the very beginning, when we have little idea about the width required by the actual text that is going to come in the columns. So we leave it to the user to adjust the widths to see the entire text. This little enhancement over the CListCtrl class makes the column widths auto adjusting to keep the entire text of all the columns visible.
Make a new Dialog based application with MFC AppWizard (exe). Then add a new class to it (Insert -> New Class). Give any fancy name you wish (I chose CMyListCtrl) and in the base class dropdown, select CListCtrl. After clicking OK you have a CListCtrl derived class. Now add the following two public functions to this class:

As we can see, this function calculates the widths of the Column Headers as well as the Items and sets the width to the larger of the two, so that complete header is visible even if no item is inserted. Also note that the last column will take all the remaining space.
To use our newly created class, first add a List Control to your dialog box (be sure to select 'Report' in the Styles page of the properties for the new control). Now, add a control variable for the newly created item (IDC_LIST1, or whatever ID you supplied) in the Member Variables page of the MFC Class Wizard (ctrl+W), but instead of accepting the default CListCtrl as the Variable type, select the new CMyListCtrl type. Call the variable m_myList. The wizard will suggest you to include the header file of your ListCtrl class in the dialog class. Do this by adding this line in the header file of your dialog class:
After this, let’s insert some columns and rows to this ListCtrl. Add the following lines at the end of OnInitDialog() of your dialog class (or wherever you need):


The call to this function makes sure all items and there headers are visible. You can play around with this example by putting different strings in the columns.
Enjoy :)
posted on 2008-08-01 10:39 Xproer-松鼠 阅读(2288) 评论(1) 编辑 收藏 举报
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 别再用vector<bool>了!Google高级工程师:这可能是STL最大的设计失误
· 单元测试从入门到精通
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 上周热点回顾(3.3-3.9)