简体   繁体   中英

Dialog create using singleton

I'm trying to create not modal dialog using singleton.

CMyDlg& CMyDlg::GetInstance()
{
    static CMyDlg myDlg;
    return myDlg;
}

then on some button press I call Create

CMyMain::OnSomeButtonPress()
{
    CMyDlg::GetInstance().Create( CMyDlg::IDD );
}

but problem is when I'm tryig to call Create twice it fails(something in wincore.cpp line 638)

What I'm doing wrong and why

CMyDlg::GetInstance().Create( CMyDlg::IDD );

can't be called twice?

CMyDlg ultimately derives from CWnd , which wraps an HWND handle. Create() method goes from "this instance doesn't represent any physical window, m_hWnd is NULL " state to "this instance corresponds to a physical window, m_hWnd is a handle to that window" state. Naturally, Create() asserts first thing that m_hWnd is, indeed, NULL .

If you want two dialogs to show up on the screen at the same time, then you need two instances of CMyDlg to represent them; you can't use a singleton. If you don't want two dialogs, then why again are you calling Create() twice?

At the end I just use pointer to dialog.

CMyDlg* m_pDlg= NULL;
CMyDlg* CMyDlg::GetInstance()
{
    m_pDlg= new CMyDlg;
    m_pDlg->Create(CMyDlg::IDD);
    return m_pDlg;
}

void CMain::OnSomeButtonPress()
{
    CMyDlg::GetInstance();
}


void CMyDlg::OnBnClickedCancel()
{
    if(m_pDlg!= NULL)
        delete m_pDlg;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM