How can you enumerate the controls in a dialog of form?

Submitted by Date of Submission User Level 

Bulent Ozkir February 8, 2001 Intermediate 

With the assumption of every control in your dialog/form is of CWnd or can be converted to CWnd, you can use the following code to enumerate controls on a form or dialog.

void CEnumControlsDlg::OnButton1() 

{

CString str1;

TCHAR szClassName[20];

int i = 0;

srand( (unsigned)time( NULL ) ); // Generate seed for rand().

for(CWnd * wnd = GetWindow(GW_CHILD); wnd != NULL; wnd = wnd->GetWindow(GW_HWNDNEXT))

{

  GetClassName(wnd->GetSafeHwnd(), szClassName, 20);

  if( 0 == _tcsicmp(szClassName, _T("Edit")) )

  {

    // change edit controls text randomly

    str1.Format("%6d string %d of edit", rand(), ++i);// Get a random number string.

    wnd->SetWindowText(str1);

  }

  else if( 0 == _tcsicmp(szClassName, _T("Button")))

  {

    // change button controls text randomly except Button1

    wnd->GetWindowText(str1);

    if( _T("Button1") == str1) continue;

    str1.Format("%6d string %d of button", rand(), ++i);// Get a random number string.

    wnd->SetWindowText(str1);

   }

   TRACE( _T("ClassName:%s\n"), szClassName );

}

}