void HideControls(int startID, int count) {
for (int i = 0; i < count; ++i) {
CWnd* pWnd = GetDlgItem(startID + i);
if (pWnd) pWnd->ShowWindow(SW_HIDE);
}
}
// 調用:隱藏 IDC_TEXT1 到 IDC_TEXT10
HideControls(IDC_TEXT1, 10);
int ids[] = { IDC_TEXT1, IDC_TEXT2, IDC_TEXT5, IDC_TEXT8, IDC_BUTTON_OK };
for (int id : ids) {
CWnd* pWnd = GetDlgItem(id);
if (pWnd) pWnd->ShowWindow(SW_HIDE);
}
class CMyDialog : public CDialog {
// ...
void ShowControls(const std::vector<int>& ids, BOOL bShow) {
int cmd = bShow ? SW_SHOW : SW_HIDE;
for (int id : ids) {
if (CWnd* p = GetDlgItem(id)) p->ShowWindow(cmd);
}
}
void EnableControls(const std::vector<int>& ids, BOOL bEnable) {
for (int id : ids) {
if (CWnd* p = GetDlgItem(id)) p->EnableWindow(bEnable);
}
}
};
GetDlgItem 返回 CWnd*,需判空防止無效 ID 導致崩潰。resource.h 中,確保數值連續或數組內 ID 均有效。CWnd::ModifyStyle(0, WS_VISIBLE) 或操作父容器(Group Box/Tab Control)統一控制。DDX_Control 變量綁定單個控件,批量操作時直接用 GetDlgItem 更靈活。核心技巧:將控件 ID 收集到數組/容器,循環調用 GetDlgItem + ShowWindow,消除重複代碼,便於維護。