How to iterate child controls in your Dialog?

23 05 2008


Assume you’ve a dialog with hundreds of child controls and you want to enable and disable them. Its not practical to get each control by control and disable them. Here iterating child controls comes to your help. Instead of getting control by control you can iterate all child controls of your dialog.


You can iterate the child windows by two methods –

1. Enumerate Child Windows
For enumeration you’ve to call the function – EnumChildWindows() by passing a callback function pointer. For each child window, the callback function will be called by passing child windows handle as parameter. See the sample code snippet.

// Enumerate Child Windows
EnumChildWindows( GetSafeHwnd(), EnumChildProc, 0 );
...

// For each child window, this callback will be called.
BOOL CALLBACK EnumChildProc( HWND hwnd, LPARAM lParam )
{
    // If you need hwnd, you can use it.
    // If you need the Control ID of child window then,
    UINT CtrlID = GetDlgCtrlID( hwnd );
    // Use the Control ID.

    return TRUE;
}

2. Get First and Next child window
If you don’t prefer a callback kind of child window iteration, then you can use – GetWindow() function. For getting the first window, you’ve to call the GetWindow() by passing GW_HWNDFIRST. For next window you should pass – GW_HWNDNEXT. You can also move backwards by using – GW_HWNDPREV. See the sample code snippet.

// Get the first child window. Use it.
HWND hwnd = ::GetWindow( GetSafeHwnd(),
                         GW_CHILD | GW_HWNDFIRST );

while( hwnd )
{
    // Get the next window. Use it.
    hwnd = ::GetWindow( hwnd, GW_HWNDNEXT );
}


While iterating in either methods you’ll get the child window handle. If you need the Ctrl ID, just call GetDlgCtrlID().


Targeted Audience – Beginners.


Actions

Information

2 responses

9 06 2008
Jijeesh

Hi,
I think this site is now famous… the first link i got from search…. help ful… 🙂

17 06 2008
Jijo.Raj

Wow!!! “I’m feeling Lucky”. 😉

Leave a comment