AfxWinInit

This function is called by the MFC-supplied WinMain function, as part of the CWinApp initialization of a GUI-based application, to initialize MFC.

BOOL AFXAPI AfxWinInit(
   HINSTANCE hInstance,
   HINSTANCE hPrevInstance,
   LPTSTR lpCmdLine,
   int nCmdShow 
);

Parameters

  • hInstance
    The handle of the currently running module.

  • hPrevInstance
    A handle to a previous instance of the application. For a Win32-based application, this parameter is always NULL.

  • lpCmdLine
    Points to a null-terminated string specifying the command line for the application.

  • nCmdShow
    Specifies how the main window of a GUI application would be shown.

Remarks

For a console application, which does not use the MFC-supplied WinMain function, you must call AfxWinInit directly to initialize MFC.

If you call AfxWinInit yourself, you should declare an instance of a CWinApp class. For a console application, you might choose not to derive your own class from CWinApp and instead use an instance of CWinApp directly. This technique is appropriate if you decide to leave all functionality for your application in your implementation of main.

Note

When it creates an activation context for an assembly, MFC uses a manifest resource provided by the user module. The activation context is created in AfxWinInit. For more information, see Support for Activation Contexts in the MFC Module State.

Example

#include <afx.h>
#include <afxdb.h>

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

   // initialize MFC and print and error on failure
   if (!AfxWinInit(::GetModuleHandle(NULL), NULL, ::GetCommandLine(), 0))
   {
      // TODO: change error code to suit your needs
      _tprintf(_T("Fatal Error: MFC initialization failed\n"));
      nRetCode = 1;
   }
   else
   {
      // try to connect to an ODBC database that doesn't exist
      // (this wouldn't work at all without initializing MFC)

      CDatabase db;
      try
      {
         db.Open(_T("This Databsae Doesn't Exist"));

         // we shouldn't realistically get here

         _tprintf_s(_T("Successful!\n")
            _T("Closing ...\n"));
         db.Close();
         _tprintf_s(_T("Closed!"));
      }
      catch (CDBException* pEx)
      {
         // we got an exception! print an error message
         // (this wouldn't work without initializing MFC)

         TCHAR sz[1024];

         _tprintf_s(_T("Error: "));
         if (pEx->GetErrorMessage(sz, 1024))
            _tprintf_s(sz);
         else
            _tprintf_s(_T("No error message was available"));
         _tprintf_s(_T("\n"));

         pEx->Delete();

         nRetCode = 1;
      }
   }

   return nRetCode;
}

Requirements

Header: afxwin.h

See Also

Reference

CWinApp Class

main: Program Startup

WinMain

Concepts

MFC Macros and Globals

CWinApp: The Application Class