c++mfcwtl

Where do I put the code to initialize my controls?


I have now tried several times to find a place where I can insert a code part which basically only adds a column to a control I have in my dialog:

void MusicPlayerDialog::InitList()
{
    m_trackList.InsertColumn(0, "Tracks");
    m_trackList.SetColumnWidth(0, 60);
}

However, so far every point I tried to insert it gives me a ::IsWindow(m_hWnd) assertion fail.

I am pretty sure this is caused by the dialog being either not initialized yet, or already destructed.

However, I would now like to know where I can insert this so it will be safely performed.

This is my snippet creating the dialog:

int WINAPI WinMain(HINSTANCE hInst, HINSTANCE hInstPrev,
    LPSTR szCmdLine, int nCmdShow)
{
    UNREFERENCED_PARAMETER(szCmdLine);
    UNREFERENCED_PARAMETER(hInstPrev);

    MusicPlayerDialog myDialog;
    MSG msg;

    myDialog.Create(NULL, NULL);

    myDialog.ShowWindow(nCmdShow);
    myDialog.UpdateWindow();

    while (GetMessage(&msg, NULL, 0, 0) > 0)
    {
        TranslateMessage(&msg);
        DispatchMessage(&msg);
    }

    return msg.wParam;
}

In here I tried it before and after the message list, but both give me the error. The one after the loop is kind of obvious, but I thought the one right in front of it works fine.

Also, I tried it in my dialogs constructor, but that was kind of expected to fail as well.

I guess the best idea so far would be to do it with the message map, something like this:

MESSAGE_HANDLER(WM_INITDIALOG, OnInit);

However, I can't find a WM_.... message which would be triggered after the window creation. I went through the list available on MSDN but from my reading there was no one which would fit properly.

The method connected to it would then call all my control initialization methods.

Can anyone point me to a solution?

EDIT:

Seems like it works when I put it in the OnInit() and perform DoDataExchange() in front of it. Still not sure if thats "the" solution


Solution

  • You should call InitList() in your MusicPlayerDialog::OnInitDialog(), which is a virtual function of CDialog:

    .h:

    virtual BOOL OnInitDialog();
    

    .cpp:

    BOOL MusicPlayerDialog::OnInitDialog()
    {
        CDialog::OnInitDialog();
    
        // more code
    
        // TODO: Add extra initialization here
        InitList();
    
        return TRUE;  // return TRUE  unless you set the focus to a control
    }