user3047190
user3047190

Reputation: 399

MFC App closes on startup

Trying to run a simple MFC App but closes because the program terminates, assuming I need to run the dialog box in a seperate thread but can't work out how.

Here's the code so far:

CWinApp theApp;

using namespace std;

int main(int argc, TCHAR* argv[], TCHAR* envp[])
{
    int nRetCode = 0;

    HMODULE hModule = ::GetModuleHandle(NULL);

    theApp.InitApplication();
    theApp.InitInstance();
    theApp.Run();

    AfxWinTerm();

    if (hModule != NULL)
    {
        // initialize MFC and print and error on failure
        if (!AfxWinInit(hModule, NULL, ::GetCommandLine(), 0))
        {
            // TODO: change error code to suit your needs
            _tprintf(_T("Fatal Error: MFC initialization failed\n"));
            nRetCode = 1;

        }
        else
        {
            MyDialog *mdlg = new MyDialog();
            mdlg->Create( IDD_MDLG, theApp.m_pMainWnd);
            mdlg->ShowWindow( true );

        }
    }
    else
    {
        // TODO: change error code to suit your needs
        _tprintf(_T("Fatal Error: GetModuleHandle failed\n"));
        nRetCode = 1;
    }

    return nRetCode;
}

There must be something simple I can do to keep the program from terminating, just not sure how?

Upvotes: 0

Views: 793

Answers (2)

Werner Henze
Werner Henze

Reputation: 16781

As far as I can see you created a Win32 Console Application and try to add a GUI to it? You should only do that if you really need the console. If not, then better create a new project, select the MFC Application template and choose dialog based application. The wizard will create all you need.

BTW, your

MyDialog *mdlg = new MyDialog();
mdlg->Create( IDD_MDLG, theApp.m_pMainWnd);
mdlg->ShowWindow( true );

should better have been:

MyDialog mdlg;
mdlg.DoModal();

No need for new in your case, so just allocate the object on the stack. And DoModal does what you want.

In my Win32 Console Application with MFC support I was able to show a dialog. But in my wizard generated code these lines were not present, so maybe you should delete them:

theApp.InitApplication();
theApp.InitInstance();
theApp.Run();

AfxWinTerm();

Upvotes: 1

marcinj
marcinj

Reputation: 50036

Instead of calling:

mdlg->ShowWindow( true );

you should do:

mdlg->DoModal();

Also, I dont think you need Create. If you want to stay with modeless dialog, then you should create message loop before returning from main - something like here http://en.wikipedia.org/wiki/Message_loop_in_Microsoft_Windows

Upvotes: 2

Related Questions