在菜單響應函數 `CTextView::OnShowCol()` 中構造 `ShowOut` 對話框對象,直接調用 `ShowOut.ShowList.InsertColumn()` 報錯。
`ShowOut` 為棧上對象,此時對話框窗口尚未創建(`DoModal`/`Create` 未調用),`ShowList` 控件對應的 `HWND` 為 `NULL`,發送 `LVM_INSERTCOLUMN` 消息失敗。
// ShowOut.h
class ShowOut : public CDialogEx {
public:
ShowOut(const vector& cols, CWnd* pParent = nullptr);
vector m_cols;
CListCtrl ShowList;
// ...
};
// ShowOut.cpp
ShowOut::ShowOut(const vector& cols, CWnd* pParent)
: CDialogEx(IDD_SHOWOUT, pParent), m_cols(cols) {}
BOOL ShowOut::OnInitDialog() {
CDialogEx::OnInitDialog();
for (int i = 0; i < m_cols.size(); ++i) {
ShowList.InsertColumn(i, m_cols[i].name, LVCFMT_LEFT, m_cols[i].width);
}
// 插入行數據...
return TRUE;
}
// 調用處
void CTextView::OnShowCol() {
vector cols = GetColumnsFromDocument();
ShowOut dlg(cols);
dlg.DoModal(); // 此處創建窗口、執行 OnInitDialog
}
MFC 列表控件動態插入數據,對話框未創建時操作控件導致失敗,正確在 OnInitDialog 初始化,構造函數傳遞數據。