Structuring Win32 GUI code

Posted by kraf on Stack Overflow See other posts from Stack Overflow or by kraf
Published on 2010-03-30T14:23:07Z Indexed on 2010/03/31 12:03 UTC
Read the original article Hit count: 332

Filed under:
|
|
|

I wish to improve my code and file structure in larger Win32 projects with plenty of windows and controls. Currently, I tend to have one header and one source file for the entire implementation of a window or dialog. This works fine for small projects, but now it has come to the point where these implementations are starting to reach 1000-2000 lines, which is tedious to browse.

A typical source file of mine looks like this:

static LRESULT CALLBACK on_create(const HWND hwnd, WPARAM wp, LPARAM lp) {
    setup_menu(hwnd);
    setup_list(hwnd);
    setup_context_menu(hwnd);

    /* clip */

    return 0;
}

static LRESULT CALLBACK on_notify(HWND hwnd, UINT msg, WPARAM wp, LPARAM lp) {
    const NMHDR* header = (const NMHDR*)lp;

    /* At this point I feel that the control's event handlers doesn't
     * necessarily belong in the same source file. Perhaps I could move
     * each control's creation code and event handlers into a separate
     * source file? Good practice or cause of confusion? */

    switch (header->idFrom) {
    case IDC_WINDOW_LIST:
        switch (header->code) {
        case NM_RCLICK:
            return on_window_list_right_click(hwnd, wp, lp);

        /* clip */
        }
    }
}

static LRESULT CALLBACK wndmain_proc(HWND hwnd, UINT msg, WPARAM wp, LPARAM lp) {
    switch (msg) {
    case WM_CREATE:
        return on_create(hwnd, wp, lp);

    case WM_CLOSE:
        return on_close(hwnd, wp, lp);

    case WM_NOTIFY:
        return on_notify(hwnd, wp, lp);

    /* It doesn't matter much how the window proc looks as it just forwards
     * events to the appropriate handler. */

    /* clip */

    default:
        return DefWindowProc(hwnd, msg, wp, lp);
    }
}

But now as the window has a lot more controls, and these controls in turn have their own message handlers, and then there's the menu click handlers, and so on... I'm getting lost, and I really need advice on how to structure this mess up in a good and sensible way.

I have tried to find good open source examples of structuring Win32 code, but I just get more confused since there are hundreds of files, and within each of these files that seem GUI related, the Win32 GUI code seems so far encapsulated away. And when I finally find a CreateWindowEx statement, the window proc is nowhere to be found.

Any advice on how to structure all the code while remaining sane would be greatly appreciated.

Thanks!

I don't wish to use any libraries or frameworks as I find the Win32 API interesting and valuable for learning.

Any insight into how you structure your own GUI code could perhaps serve as inspiration.

© Stack Overflow or respective owner

Related posts about c

    Related posts about win32